POJ1703 Find them, Catch them

本文探讨了如何使用并查集解决一类特定的问题——通过理解敌人的敌人是朋友的原则来判断个体间的关系。文章提供了详细的代码实现,并解释了如何根据输入指令更新并查集以确定两个个体是否在同一阵营或是不同阵营。

    原题传送:http://poj.org/problem?id=1703

    并查集。

    这题更加深了对并查集的理解,以前做过差不多的类似“朋友传递”的题。这道题核心的一句话是:敌人的敌人是朋友。那么假设每个x总有一个敌人(编号为x+n),那么可以把a加入到b的敌人b+n代表的并查集中,把b加入到a的敌人a+n的并查集中。如果find(a)==find(b),那么a和b是同gang;如果find(a)==find(b+n)或者find(b)==find(a+n),那么a和b是不同的gangs;否则,not sure。

View Code
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #define M 100010
 5 using namespace std;
 6 int f[M << 1];
 7 
 8 int find(int x)
 9 {
10     return x == f[x] ? f[x] : f[x] = find(f[x]);
11 }
12 
13 int main()
14 {
15     int T, m, a, b, n;
16     char cmd[3];
17     scanf("%d", &T);
18     while (T --)
19     {
20         scanf("%d%d", &n, &m);
21         for (int i = 0; i <= 2 * n; i++)
22             f[i] = i;
23         while (m--)
24         {
25             scanf("%s%d%d", cmd, &a, &b);
26             if (cmd[0] == 'D')
27             {
28                 f[find(a)] = find(b + n);
29                 f[find(b)] = find(a + n);
30             }
31             else
32             {
33                 if(find(a) == find(b))
34                     puts("In the same gang.");
35                 else if(find(a) == find(b + n) || find(a + n) == find(b))
36                     puts("In different gangs.");
37                 else
38                     puts("Not sure yet.");
39             }
40         }
41     }
42     return 0;
43 }

转载于:https://www.cnblogs.com/huangfeihome/archive/2012/09/07/2674586.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值