题目描述:
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.
输入:
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.
输出:
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.”
样例输入:
1
5 5
A 1 2
D 1 2
A 1 2
D 2 4
A 1 4
样例输出:
Not sure yet.
In different gangs.
In the same gang.
这里将0~n表示为一个帮派,n–2n表示为另一个帮派,既然D x y即表示为这两个分属不同的帮派,那么x+n就是和y为同一个帮派,x和y+n就是另一个帮派,与挑战程序设计这本书中88页所说的食物链问题为同一个类型问题
在本题依旧不是很懂的同学可以看一下
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int n,k;
int father[200050];
void init(int x)
{
for(int i=0;i<=200000;i++)
{
father[i]=i;
}
}
int findd(int a)
{
if(father[a]==a)return a;
else return father[a]=findd(father[a]);
}
void unit(int a,int b)
{
a=findd(a);
b=findd(b);
if(a==b)return ;
father[a]=b;
}
bool same(int x,int y)
{
return findd(x)==findd(y);
}
int main()
{
int ttt;
scanf("%d",&ttt);
while(ttt--)
{
scanf("%d%d",&n,&k);
char bb[2];
init(n);
for(int i=0;i<k;i++)
{
scanf("%s",bb);
int a,b;
scanf("%d%d",&a,&b);
if(bb[0]=='D')
{
unit(a,b+n);
unit(a+n,b);
}
else
{
if(same(a,b))
{
printf("In the same gang.\n");
}
else if(same(a,b+n))
{
printf("In different gangs.\n");
}
else
{
printf("Not sure yet.\n");
}
}
}
}
return 0;
}