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

题目地址:POJ 1703

种类并查集水题。

代码例如以下:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <algorithm>

using namespace std;
int bin[600000], rank[600000];
int find1(int x)
{
    int y;
    if(bin[x]!=x)
    {
        y=bin[x];
        bin[x]=find1(bin[x]);
        rank[x]=rank[x]^rank[y];
    }
    return bin[x];
}
int main()
{
    int t, n, m, i, a, b, f1, f2;
    char c;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        for(i=1;i<=n;i++)
        {
            bin[i]=i;
            rank[i]=0;
        }
        while(m--)
        {
            getchar();
            scanf("%c%d%d",&c,&a,&b);
            f1=find1(a);
            f2=find1(b);
            if(c=='D')
            {
                if(f1!=f2)
                {
                    bin[f2]=f1;
                    rank[f2]=rank[a]^rank[b]^1;
                }
            }
            else
            {
                if(f1!=f2)
                {
                    printf("Not sure yet.\n");
                }
                else
                {
                    if(rank[a]!=rank[b])
                        puts("In different gangs.");
                    else
                        puts("In the same gang.");
                }
            }
        }
    }
    return 0;
}


posted on 2017-07-04 14:10  wgwyanfs  阅读(110)  评论(0编辑  收藏  举报

导航