Find them, Catch them
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 42920 Accepted: 13195
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:
D [a] [b]
where [a] and [b] are the numbers of two criminals, and they belong to different gangs.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.
题意:
给出n个人,D给给出x和y是不同一个帮派的,A是询问x和y是不是一个帮派。
解题思路:
如果x和y存在关系,就放到一个并查集里面。
多用一个flag数组存该点与父亲的关系,如果相同帮派就为0,如果不同帮派,就为1.
那么在每次更新的时候,从祖先的第一个孙子开始转移状态。知道了父亲和爷爷的关系,儿子和父亲的关系,就知道了儿子和爷爷的关系,并把儿子挂到爷爷上。
对于两个并查集的合并,知道了两个父亲的关系,就知道了两个爷爷的关系,并把爷爷a并到爷爷b上。
AC代码:
#include<stdio.h>
#include<algorithm>
using namespace std;
const int maxn = 1e5+5;
int fa[maxn];
int flag[maxn];
int Find(int x)
{
if(x == fa[x]) return x;
int tmp = fa[x];
fa[x] = Find(fa[x]);
flag[x] = flag[x]^flag[tmp];
return fa[x];
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,loop;
scanf("%d%d",&n,&loop);
for(int i = 1;i <= n;i++) fa[i] = i,flag[i] = 0;
while(loop--)
{
getchar();
char op;
int a,b;
scanf("%c %d %d",&op,&a,&b);
if(op == 'A')
{
if(Find(a) == Find(b))
{
if(flag[a] == flag[b]) printf("In the same gang.\n");
else printf("In different gangs.\n");
}
else printf("Not sure yet.\n");
}
else
{
int root_a = Find(a),root_b = Find(b);
if(root_a > root_b) swap(root_a,root_b);
fa[root_b] = root_a;
flag[root_b] = !(flag[a]^flag[b]);
}
}
}
return 0;
}