您的位置:首页 > 其它

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

2017-01-31 21:58 363 查看
Find them, Catch them

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 43447 Accepted: 13366
Description

The police office in Tadu City decides to say ends to the chaos, as launch actions to root up the TWO gangs in the city, Gang Dragon and Gang Snake. However, the police first needs to identify which gang a criminal belongs to. The present question is, given
two criminals; do they belong to a same clan? You must give your judgment based on incomplete information. (Since the gangsters are always acting secretly.) 

Assume N (N <= 10^5) criminals are currently in Tadu City, numbered from 1 to N. And of course, at least one of them belongs to Gang Dragon, and the same for Gang Snake. You will be given M (M <= 10^5) messages in sequence, which are in the following two kinds: 

1. D [a] [b] 

where [a] and [b] are the numbers of two criminals, and they belong to different gangs. 

2. A [a] [b] 

where [a] and [b] are the numbers of two criminals. This requires you to decide whether a and b belong to a same gang. 

Input

The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. Each test case begins with a line with two integers N and M, followed by M lines each containing one message as described above.
Output

For each message "A [a] [b]" in each case, your program should give the judgment based on the information got before. The answers might be one of "In the same gang.", "In different gangs." and "Not sure yet."
Sample Input
1
5 5
A 1 2
D 1 2
A 1 2
D 2 4
A 1 4

Sample Output
Not sure yet.
In different gangs.
In the same gang.

Source
POJ Monthly--2004.07.18

题意:有两个犯罪团体。语句“A a b”表示a和b不在一个团体;语句“D a b”要询问a和b是否在一个团体,对于此语句,要输出三种结果之一(在同一团体,不在同一团体,不确定)。

思路:与题目食物链类似,设元素i和i+n分别表示i属于团体一和i属于团体二。如果a和b属于同一团体,则合并a与b,a+n与b+n;如果a和b不在同一团体,则合并a与b+n,a+n与b。最后进行判断即可。

#include<cstdio>
#include<vector>
#include<algorithm>
#include<map>
#include<cmath>
#include<cstring>
#include<sstream>
#include<iostream>
using namespace std;

const int maxn = 1e5 + 10;
int fa[2*maxn];
int n, m;

void init()
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= 2*n+2; i++) fa[i] = i;
}

int find(int x)
{
return fa[x] == x ? fa[x] : fa[x] = find(fa[x]);
}

void Union(int a, int b)
{
int x = find(a), y = find(b);
fa[y] = x;
}

int main()
{
int T;
scanf("%d", &T);
char s[5];
int a, b;
while(T--) {
init();
while(m--) {
scanf("%s%d%d", s, &a, &b);
if(s[0] == 'D') {
Union(a, b+n);
Union(a+n, b);
}
else {
int a1 = find(a), b1 = find(b), a2 = find(a+n), b2 = find(b+n);
if(a1 == b1 || a2 == b2) printf("In the same gang.\n");
else if(a1 == b2 || a2 == b1) printf("In different gangs.\n");
else printf("Not sure yet.\n");
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: