您的位置:首页 > 其它

poj 1703 : Find them Catch them (并查集)

2017-05-21 14:01 337 查看
今天5,21啊,苦逼在做题,居然还一直wrong,我靠。昨晚熬夜看比赛,今天心态有点炸,不行了。

前言:wa了好多次,T了好多次,题目收藏下吧,不难理解。用opp数组来标记位置,不能用cin

思路:并查集的应用。关键:用opp[x]表示一个与x处于不同帮派的人的编号,只需要1个就够了,因为只需要这么1个编号就能找出它的集合代表,若y的集合代表与之相同,则x与y为不同帮派。

代码

#include<iostream>
using namespace std;
const int Max = 100050;

int n, m;
int parent[Max], opp[Max]; // 用于记录x1个不同帮派opp[x],若没有x的信息则初始化为opp[x] = 0。

void make_set(){
for(int x = 1; x <= n; x ++){
parent[x] = x;
opp[x] = 0;
}
}

int find_set(int x){
if(x != parent[x])
parent[x] = find_set(parent[x]);
return parent[x];
}

void union_set(int x, int y){
x = find_set(x);
y = find_set(y);
if(x == y) return;
parent[y] = x;
}

int main(){
int t, x, y;
scanf("%d", &t);
while(t --){
scanf("%d %d", &n, &m);
getchar();
make_set();
while(m --){
char c;
scanf("%c %d %d", &c, &x, &y);
getchar(); // 记得要回收回车号。
if(c == 'D'){
if(opp[x] == 0 && opp[y] == 0){ // 情况1:x,y在前面都没有信息。
opp[x] = y;
opp[y] = x;
}
else if(opp[x] == 0){ // 情况2:x在前面都没有信息,而y有。
opp[x] = y;
union_set(x, opp[y]);
}
else if(opp[y] == 0){ // 情况3:y在前面都没有信息,而x有。
opp[y] = x;
union_set(y, opp[x]);
}
else{ // 情况4:x,y在前面都有信息。
union_set(x, opp[y]);
union_set(y, opp[x]);
}
}
if(c == 'A'){ // 注意三种情况的判断依据。
if(find_set(x) == find_set(y))
printf("In the same gang.\n");
else if(find_set(x) == find_set(opp[y]))
printf("In different gangs.\n");
else
printf("Not sure yet.\n");
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: