Codeforces Round #286 (Div. 2) B. Mr. Kitayuta's Colorful Graph dfs

思路:因为color种类不超过100种,根据题目数据量,直接对每种color进行枚举,再进行dfs判断该种颜色下两点是否连通即可。

代码如下:

#include <cstdio>
#include <cstring>
using namespace std;
#define N 105
int head[N][N], idx;
struct Edge{
    int to, next;
}edges[N * 2];
bool vis[N];

void add(int from, int to, int color){
    ++idx;
    edges[idx].to = to, edges[idx].next = head[from][color], head[from][color] = idx;
}

bool is_connected(int u, int v, int color){
    vis[u] = true;
    for(int i = head[u][color]; i != 0; i = edges[i].next){
        int to = edges[i].to;
        if(to == v)
            return true;
        if(!vis[to] && is_connected(to, v, color))
            return true;
    }
    return false;
}

int main(){
    int n, m, q;
    scanf("%d %d", &n, &m);
    for(int i = 0; i < m; ++i){
        int v1, v2, color;
        scanf("%d %d %d", &v1, &v2, &color);
        add(v1, v2, color);
        add(v2, v1, color);
    }
    scanf("%d", &q);
    for(int i = 0; i < q; ++i){
        int u, v, ans = 0;
        scanf("%d %d", &u, &v);
        for(int j = 1; j <= m; ++j){
            memset(vis, false, sizeof(vis));
            if(is_connected(u, v, j))
                ans ++;
        }
        printf("%d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(搜索,图论,DFS,codeforces)