您的位置:首页 > 其它

uva 10158 - War(并查集)

2013-10-15 23:27 381 查看
题目链接:10158 - War

题目大意:有n个人,若干个命令,每个人分属于不同的国家,并且代表国家与其他代表会谈,这将决定国与国之间的同盟关系,1:a与b结盟  2:a与b决裂(成为敌人) 3:判断a与b是否为同盟(不包括不确定) 4:判断a与b是否为敌人。

注意:同盟的同盟是同盟,敌人的敌人是朋友。添加新的关系时与已有的关系冲突的话输出-1。

解题思路:开一个2 * n的数组,0~n - 1表示的是同盟,n~2 * n - 1表示的是n个国家的敌人。

#include <stdio.h>
#include <string.h>
const int N = 100005;
int n, f[N * 2];

int getfather(int x) {
return x == f[x] ? x : f[x] = getfather(f[x]);
}

void setfirend(int x, int y) {
int pf = getfather(x), qf = getfather(y);
int pe = getfather(x + n), qe = getfather(y + n);

if (pe == qf || qe == pf) {
printf("%d\n", -1);
return;
}

f[pf] = qf;
f[pe] = qe;
}

void setenemies(int x, int y) {
int pf = getfather(x), qf = getfather(y);
int pe = getfather(x + n), qe = getfather(y + n);

if (pf == qf || pe == qe) {
printf("%d\n", -1);
return;
}

f[pf] = qe;
f[qf] = pe;
}

void isfirend(int x, int y) {
int pf = getfather(x), qf = getfather(y);
printf("%d\n", pf == qf ? 1 : 0);
}

void isenemies(int x, int y) {
int pf = getfather(x), qe = getfather(y + n);
printf("%d\n", pf == qe ? 1 : 0);
}

int main () {
scanf("%d", &n);
int cas, a, b;
for (int i = 0; i < n; i++) f[i] = i, f[i + n] = i + n;
while (scanf("%d%d%d", &cas, &a, &b), cas || a || b) {
switch(cas) {
case 1:
setfirend(a, b);
break;
case 2:
setenemies(a, b);
break;
case 3:
isfirend(a, b);
break;
case 4:
isenemies(a, b);
break;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: