POJ 1073 Find them, Catch them

并查集维护不同集合之间的关系,类似食物链,但是最后判断的逻辑要搞清楚。

#include <cstdio>
int t, n, m, father[200010], a, b;
char c;
int findfather(int x)
{
    if(x == father[x]) return x;
    else{
        int f = findfather(father[x]);
        father[x] = f;
        return f;
    }
}
void Union(int a, int b)
{
    int f1 = findfather(a), f2 = findfather(b);
    if(f1 != f2) father[f1] = f2;
}
bool same(int a, int b)
{
    if(findfather(a) == findfather(b)) return true;
    else return false;
}
int main()
{
    scanf("%d", &t);
    for(int i = 0; i < t; i++){
        scanf("%d%d", &n, &m);
        for(int j = 1; j <= n; j++){
            father[j] = j;
            father[j + n] = j + n;
        }
        for(int j = 0; j < m; j++){
            getchar();
            scanf("%c%d%d", &c, &a, &b);
            if(c == 'D') Union(a, b + n), Union(a + n, b);
            else{
                if(same(a, b)) printf("In the same gang.\n");
                else if(same(a, b + n)) printf("In different gangs.\n");
                else printf("Not sure yet.\n");
            }
        }
    }
    return 0;
}
发布了29 篇原创文章 · 获赞 0 · 访问量 366

猜你喜欢

转载自blog.csdn.net/qq_33942309/article/details/105660603