POJ 1703 Find them, Catch them

并查集应用。

这个题目和【食物链】类似。

    a[x] = 0  表示x与父节点同gang
    a[x] = 1 表示与父节点不同gang


#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 100005;
int set[MAXN], a[MAXN];

int Find_set(int x) {
    if (x == set[x]) return x;
    int t = Find_set(set[x]);
    a[x] = (a[set[x]] + a[x]) % 2;
    return set[x] = t;
}
void Union(int x, int y) {
    int fx = Find_set(x);
    int fy = Find_set(y);
    set[fx] = fy;
    if (a[y] == 0)
        a[fx] = 1 - a[x];
    else a[fx] = a[x];
}
int main() {
    int t, n, m, fx, fy, x, y;
    char ch;

    scanf("%d", &t);
    while ( t-- ) {
        scanf("%d %d", &n, &m);
        for (int i=1; i<=n; i++) {
            set[i] = i;
            a[i] = 0;
        }
        while ( m-- ) {
            scanf(" %c %d %d", &ch, &x, &y);
            if (ch == 'A') {
                fx = Find_set(x);
                fy = Find_set(y);
                if (fx != fy)
                    printf("Not sure yet.\n");
                else if (a[x] == a[y])
                    printf("In the same gang.\n");
                else printf("In different gangs.\n");
            } else Union(x, y);
        }
    }
    return 0;
}


你可能感兴趣的:(POJ 1703 Find them, Catch them)