uva 10158 - War(并查集)

来源:互联网 发布:java能做嵌入式开发吗 编辑:程序博客网 时间:2024/05/14 01:40

题目链接: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;}