POJ 1703 Find them, Catch them(并差集)

带关系的并差集.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <string>
#define LL long long
#define DB double
#define SF scanf
#define PF printf
#define N 100009
using namespace std;
int fa[N],rt[N];
int finfa(int k)
{
    if(k==fa[k]) return k;
    int t = finfa(fa[k]);
    rt[k] = (rt[k]+rt[fa[k]])%2;
    return fa[k] = t;
}
void un(int x,int y)
{
    int a = finfa(x),b = finfa(y);
    if(a==b) return ;
    fa[a] = b;
    rt[a]=(rt[x]+rt[y]+1)%2;
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif
    int cas;SF("%d",&cas);
    char ch[4];int a,b;
    int n,m;
    while(cas--)
    {
        SF("%d%d",&n,&m);
        for(int i=0;i<=n;i++) fa[i] = i,rt[i] = 0;
        while(m--)
        {
            SF("%s%d%d",ch,&a,&b);
            if(ch[0]=='A')
            {
                if(finfa(a)!=finfa(b))
                {
                    PF("Not sure yet.\n");
                }else
                {
                    if(rt[a]==rt[b])
                    PF("In the same gang.\n");
                    else
                    PF("In different gangs.\n");
                }
            }else
            {
                un(a,b);
            }
        }
    }
    return 0;
}


你可能感兴趣的:(数据结构)