您的位置:首页 > 其它

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

2014-04-11 14:06 429 查看
http://blog.csdn.net/freezhanacmore/article/details/8774033?reload 这篇讲解非常好,我也是受这篇文章的启发才做出来的。



代码:





#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define N 100100

int fa
,same
;

void makeset(int n)
{
    for(int i=1;i<=n;i++)
    {
        fa[i] = i;
        same[i] = 0;
    }
}

int findset(int x)
{
    if(x != fa[x])
    {
        int tmp = fa[x];
        fa[x] = findset(fa[x]);
        same[x] = (same[x] + same[tmp])%2;
    }
    return fa[x];
}

int unionset(char s,int a,int b)
{
    int x = findset(a);
    int y = findset(b);
    if(x == y)    //属于同一个集合
    {
        if(s == 'A')
        {
            if(same[a] == same[b])
            {
                return 1;  //same
            }
            else
            {
                return 0;  //different
            }
        }
    }
    else  //不属于同一个集合
    {
        if(s == 'A')
        {
            return 2;    //unsure
        }
        else if(s == 'D')
        {
            fa[x] = y;
            same[x] = (same[a] + same[b] + 1)%2;
        }
    }
    return 3;  //要加,这是对其他情况的处理,因为此函数必须返回一个值
}

int main()
{
    int t,n,m,i;
    char ss[5];
    int a,b;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        makeset(n);
        for(i=0;i<m;i++)
        {
            scanf("%s %d %d",ss,&a,&b);
            if(unionset(ss[0],a,b) == 1)
            {
                cout<<"In the same gang."<<endl;
            }
            else if(unionset(ss[0],a,b) == 0)
            {
                cout<<"In different gangs."<<endl;
            }
            else if(unionset(ss[0],a,b) == 2)
            {
                cout<<"Not sure yet."<<endl;
            }
        }
    }
    return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: