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

本文详细介绍了并查集算法的基本概念、实现原理及代码实现,并通过具体的应用实例展示了如何利用并查集解决实际问题。文章首先给出了并查集的数据结构定义,接着解释了并查集中的两个核心操作——查找和合并的具体实现方法,最后通过一段示例代码展示了如何在程序中使用并查集。

http://blog.youkuaiyun.com/freezhanacmore/article/details/8774033?reload  这篇讲解非常好,我也是受这篇文章的启发才做出来的。

 

代码:

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

int fa[N],same[N];

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

 

转载于:https://www.cnblogs.com/whatbeg/p/3498416.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值