POJ 1703 Find them, catch them (并查集)

本文深入探讨了使用并查集解决包含多个集合的编程问题,特别关注如何有效管理不同集合间成员的敌我关系,避免简单地将所有敌人为一集合,所有友人为另一集合的误区。通过实例分析和代码实现,展示了如何通过记录每个成员与其父亲节点的关系来追踪集合间的敌我状态。

  题目: Find them,Catch them

  刚开始以为是最基本的并查集,无限超时。

  这个特殊之处,就是可能有多个集合。

  比如输入D 1 2  D 3 4 D 5 6...这就至少有3个集合了。并且任意2个集合之间成员的敌我关系不明。

  这里每个集合里面的成员关系要记录,他们在一个集合里,只是因为他们关系明确,敌人或者朋友。

  千万不要简单的认为成朋友在一个集合,敌人在另外一个集合,分成2个集合。因为题目说只有2个匪帮,很容易进入这个误区。

  我们只要记录一个成员和自己父亲的敌我关系和建树就可以了。

  

代码:

#include<iostream>
#include<cstdio>
using namespace std;
const int MM = 100001;
int father[MM];
int relation[MM];


int find(int x)
{
    if(x == father[x]) return x;
    int r = find(father[x]);
    relation[x] ^= relation[father[x]];
    return father[x] = r;
}

void join(int x, int y)
{
    int fx = find(x);
    int fy = find(y);
    
    father[fx] = fy;
    if(relation[y] == 1)
        relation[fx] = relation[x]; 
    else
        relation[fx] = 1 - relation[x];
}


void solve()
{
    int T,N,M,i,a,b,ta,tb;
    char str;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d %d",&N, &M);
        
        for(i = 1; i <= N; ++i)
        {
            father[i] = i;
            relation[i] = 0;
        }
        
        for(i = 0; i < M; ++i)
        {
            getchar();
            scanf("%c %d %d", &str, &a, &b);
            if(str == 'D')
                join(a, b);
            else
            {
                ta = find(a);
                tb = find(b);
                if(ta == tb)
                {
                    if(relation[a] == relation[b])
                        printf("In the same gang.\n");
                    else
                        printf("In different gangs.\n");
                }   
                else
                    printf("Not sure yet.\n");
            }
        }
    }
}

int main()
{
    solve();
    return 0;
}

 

转载于:https://www.cnblogs.com/HpuAcmer/p/4172775.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值