Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 20441 | Accepted: 6052 |
Description
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
Output
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
#include <iostream>
#include <stdio.h>
#define N 100005
using namespace std;
int rank[N];
int foe[N];
int f[N];
int n;
void init(){
for(int i = 1; i <= n ; i++){
rank[i] = 0;
foe[i] = -1;
f[i] = i;
}
}
int find(int x){
if( x == f[x]) {
return x;
} else {
return f[x] = find(f[x]);
}
}
void merge(int a, int b){
int ra = find(a);
int rb = find(b);
if(ra != rb){
if(rank[ra] < rank[rb]){
f[ra] = rb;
} else {
f[rb] = ra;
if(rank[rb] == rank[ra]){
rank[ra]++;
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
int m;
scanf("%d%d",&n,&m);
init();
char command;
int a;
int b;
for(int i = 0; i < m;i++){
getchar();
command = getchar();
scanf("%d%d",&a,&b);
if( command == 'A') {
if( find(a) == find(b)){
printf("In the same gang.\n");
} else {
if( foe[a] == -1 || foe[b] == -1 || find(a) != find(foe[b])){
printf("Not sure yet.\n");
} else {
printf("In different gangs.\n");
}
}
} else {
if(foe[a] == -1){
foe[a] = b;
}
if(foe[b] == -1){
foe[b] = a;
}
merge(a,foe[b]);
merge(b,foe[a]);
}
}
}
return 0;
}