POJ 1703

1703

并查集

#include <stdio.h>
#include <string.h>

#define bclear(a,b) memset(a,b,sizeof(a))
#define maxn 100001

int fa[maxn],enemy[maxn];

int getfa(int a){
    if (fa[a]==a) {
        return a;
    }else{
        fa[a]=getfa(fa[a]);
    }
    return fa[a];
}

int judge(int a,int b){
    return getfa(a)==getfa(b);
}

void unite(int a,int b){
    fa[getfa(b)]=getfa(a);
}

void work(){
    int m,n,i,b,a;
    char ch;
    
    bclear(enemy,0);
    
    scanf("%d%d",&n,&m);
    for (i=1; i<=n; i++) {//初始化并查集
        fa[i]=i;
    }
    for (i=1; i<=m; i++) {
        getchar();
        scanf("%c%d%d",&ch,&a,&b);
        if (ch=='D') {
            if (enemy[a]) {
                unite(enemy[a], b);
            }
            if (enemy[b]) {
                unite(enemy[b], a);
            }
            enemy[a]=b;
            enemy[b]=a;
        }else{
            if (getfa(a)==getfa(enemy[b])) {
                printf("In different gangs.\n");
            }else if (getfa(a)==getfa(b)){
                printf("In the same gang.\n");
            }else{
                printf("Not sure yet.\n");
            }
        }
    }
    return;
}

int main(){
    int k;
    scanf("%d",&k);
    while (k--) {
        work();
    }
    return 0;
}




你可能感兴趣的:(POJ 1703)