2017年3月16日 | ljfcnyali
题目大意:Tadu City里面有两个黑帮团伙Gang Dragon和Gang Snake,一共有n名团伙成员(还不知道属于这两个黑帮的哪一个)。现在警察局有一些信息,每条信息包含2个人编号,表示这2个人属于不同的帮派。问给你2个人的编号,能否确定他们是否属于同一个帮派。
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.
题目分析:并查集的应用。关键:用opp[x]表示一个与x处于不同帮派的人的编号,只需要1个就够了,因为只需要这么1个编号就能找出它的集合代表,若y的集合代表与之相同,则x与y为不同帮派。
AC代码:
/*************************************************************************
> File Name: POJ1073.cpp
> Author: ljf-cnyali
> Mail: ljfcnyali@gmail.com
> Created Time: 2017/3/16 20:31:18
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<queue>
using namespace std;
#define REP(i, a, b) for(int i = (a), _end_ = (b);i <= _end_; ++ i)
#define mem(a) memset((a), 0, sizeof(a))
#define str(a) strlen(a)
const int maxn = 100050;
int n, m;
int f[maxn], w[maxn];
int cha(int x) {
return x == f[x] ? x : f[x] = cha(f[x]);
}
void Set(int x, int y) {
x = cha(x);
y = cha(y);
if(x == y)
return ;
else
f[y] = x;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
scanf("%d", &t);
while(t--) {
scanf("%d%d", &n, &m);
mem(w);
REP(i, 1, n)
f[i] = i;
int x, y;
char c;
REP(i, 1, m) {
getchar();
c = getchar();
scanf("%d%d", &x, &y);
if(c == 'D')
if(w[x] == 0 && w[y] == 0) {
w[x] = y;
w[y] = x;
}
else if(w[x] == 0) {
w[x] = y;
Set(x, w[y]);
}
else if(w[y] == 0) {
w[y] = x;
Set(y, w[x]);
}
else {
Set(x, w[y]);
Set(y, w[x]);
}
else
if(cha(x) == cha(y))
printf("In the same gang.\n");
else if(cha(x) == cha(w[y]))
printf("In different gangs.\n");
else
printf("Not sure yet.\n");
}
}
return 0;
}