poj 1703 Find them, Catch them 并查集

 

#include <stdio.h>
#define maxn 100010
int p[maxn],rank[maxn];
int find(int x)
{
    if(x==p[x]) return x;
    else
    {
        int tmp=p[x];
        p[x]=find(p[x]);
        rank[x]=(rank[x]+rank[tmp])%2;
        return p[x];
    }
}
void link(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    p[fx]=fy;
    if(rank[y]==0) rank[fx]=1-rank[x];
    else rank[fx]=rank[x];
}
int main()
{
    int t;
    int i;
    int x,y;
    scanf("%d",&t);
    while(t--)
    {
        int n,m;
        scanf("%d%d",&n,&m);
        for(i=1;i<=n;i++)
        {
            p[i]=i;
            rank[i]=0;
        }
        char c;
        getchar();
        for(i=1;i<=m;i++)
        {
            scanf("%c%d%d",&c,&x,&y);
            if(c=='D')
                link(x,y);
            else
            {
                int fx=find(x);
                int fy=find(y);
                if(fx!=fy) printf("Not sure yet.\n");
                else if(rank[x]==rank[y]) printf("In the same gang.\n");
                else printf("In different gangs.\n");
            }
            getchar();
        }
    }
    return 0;
}


 

posted @ 2014-05-07 22:01  贝尔摩德  阅读(130)  评论(0编辑  收藏  举报