http://poj.org/problem?id=1703
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.
题目大意:某个地方有两个团伙,输入A x y,让你判断x与y的关系并输出相应的语句;输入D x y,表示x与y在不同的团伙。
思路: 带权并查集, relation[i]表示i与根结点的关系,0代表i与根结点在同一集团,1代表i与根结点在不同集团。初始化另relation[i]=0。 这里只说一下判断的情况, 推理过程跟向量合成很像, 可以看我的另外两篇博客。 输入A x y, 当x与y的根结点不相同时, 这时候不能判断x和y的关系,输出Not sure yet; 当x与y的根结点相同时,根据relation[x]和relation[y]的关系来判断,当relation[x]=relation[y]=0时,x与y在同一团伙,当relation[x]=relation[y]=1时,x与y也在同一团伙。(x与根不同 y与根不同 所以x与y相同)这时候输出In the same gang;否则输出In different gangs。
relation关系的推导:
https://blog.csdn.net/xiji333/article/details/86650735
https://blog.csdn.net/xiji333/article/details/86653185
顺带一提,这道题是卡cin的。
#include<iostream>
#include<cstdio>
#include<string>
#include<cmath>
using namespace std;
int f[100005];
int relation[100005];
int n;
void init()
{
for(int i=1;i<=n;i++)
{
f[i]=i;
relation[i]=0; //0与根同一集团 1 与根不同集团
}
}
int Find(int x)
{
if(f[x]==x)
return x;
int temp=f[x];
f[x]=Find(f[x]);
relation[x]=(relation[x]+relation[temp])%2;
return f[x];
}
void Union(int x,int y)
{
int fx=Find(x),fy=Find(y);
if(fx!=fy)
{
f[fx]=fy;
relation[fx]=(-relation[x]+1+relation[y])%2;
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int k;
scanf("%d%d",&n,&k);
init();
char D;
int t1,t2;
for(int i=0;i<k;i++)
{
getchar();
D=getchar();
scanf("%d%d",&t1,&t2);
if(D=='A')
{
int fx=Find(t1),fy=Find(t2);
if(fx!=fy)
printf("Not sure yet.\n");
else
{
if(relation[t1]==relation[t2])
printf("In the same gang.\n");
else
printf("In different gangs.\n");
}
}
else //不同团伙
Union(t1,t2);
}
}
return 0;
}