您的位置:首页 > 其它

poj--1703 Find them, Catch them(并查集)

2016-11-25 23:32 381 查看
problem link

题解

对于
D a b
,a和b属于不同的帮派,如果
a
属于帮派A,那么
a + n
属于帮派B,同理,b也是如此。

因此,并查集中元素的个数是
2n
,每次合并就是
Union(a, b + n) 和 Union(a + n, b)


这实际上是保留了所有的可能性,因为只知道
a
b
不在同一个集合里,不能确定到底是属于哪个集合。

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
using namespace std;

const int maxn = 100000 + 5;
int p[2 * maxn];
int n, m;

int find(int x) { return x == p[x] ? x : p[x] = find(p[x]); }
void Union(int x, int y){
x = find(x), y = find(y);
if(x != y) p[x] = y;
}

int main(){
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif // ONLINE_JUDGE
// 1500K    672MS
int t;
for(cin >> t; t--; ){
cin >> n >> m;
for(int i = 0; i <= 2 * n; ++i) p[i] = i;
char op;
int a, b;
for(int i = 0; i < m; ++i){
getchar();
scanf("%c %d %d", &op, &a, &b);
if(op == 'A'){
if(find(a) == find(b)){
printf("In the same gang.\n");
}
else if(find(a) == find(b + n)) printf("In different gangs.\n");
else printf("Not sure yet.\n");
}
else{
Union(a, b + n);
Union(a + n, b);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 并查集