poj 1703 Find them, Catch them(种类并查集)

接上文:食物链的多种类并查集.http://blog.csdn.net/cqlf__/article/details/7381467

本题比上面那题要简单.原理都是一样的都是种类并查集。

/*
Problem ID:H - Find them, Catch them
meaning: 两个黑班。D:a,b different A:ask diff or same 
Analyzing:种类并查集,
*/
#include <iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>

using namespace std;
typedef struct even{int pi,di;}even;

#define FOR(i,s,t) for(int i=(s); i<(t); i++)
#define BUG puts("here!!!")
#define print(x) printf("%d\n",x)
#define LL long long
#define maxn 100005

int pre[maxn],rela[maxn];
void init(){
    FOR(i,0,maxn){pre[i]=-1;rela[i]=0;}
}

int find(int x){
    int s=x;
    if(pre[x]<0) return x;
    s=find(pre[x]);
    rela[x]=rela[x]^rela[pre[x]];//或者这样: rela[x]=(rela[x]+rela[pre[x]])%2;
    return pre[x]=s;
}

void Union(int R1,int R2){
    int r1=find(R1);
    int r2=find(R2);//bug
    if(r1==r2) return;
    pre[r1]=r2;
    rela[r1]=~(rela[R2]^rela[R1])// rela[r1]=(rela[R2]-rela[R1]+1)%2;
}
int main(){
    int T,N,M,num1,num2;
    char op[5];
    scanf("%d",&T);
    while(T--){
        init();
        scanf("%d%d",&N,&M);
        while(M--){
            scanf("%s%d%d",op,&num1,&num2);
            if(op[0]=='A') {
                if(N==2) printf("In different gangs.\n");//一个帮派至少要有一人。。。T_T实际上没加也没关系.
                if(find(num1)==find(num2)) {
                    if(rela[num1]!=rela[num2]) printf("In different gangs.\n");
                    else    printf("In the same gang.\n");
                }
                else    printf("Not sure yet.\n");
            }
            else    Union(num1,num2);
        }
    }
	return 0;
}


你可能感兴趣的:(struct)