您的位置:首页 > 其它

poj 1703 Find them, Catch them(带权并查集)

2014-04-22 23:13 369 查看
题目: poj 1703 Find them, Catch them(带权并查集)

题目大意:题目已知有两个帮派,D x y 代表这两个属于不同的帮派,A X Y 是询问X Y 属于相同还是不同还是不确定的帮派。

解题思路:这题要用到带权并查集,例如 c【x】= 1 的话就说明他与根是不属于同一个帮派的,0就反之。 每次给出一个D X Y 的话就需要把 c【q】 = ( c[x] + c[y] + 1 ) % 2; 例如如果x, y属于不同的帮派,然后x与他的根属于相同的帮派,y 与他的根属于不同的帮派,那么 q 和p 就是属于相同的帮派, c【q】 = (1 + 0 + 1) % 2 = 0;

代码:

#include <stdio.h>

const int N = 100005;
int t, n, m, f
, c
;

void init () {

for (int i = 0; i <= n; i++) {

f[i] = i;
c[i] = 0;
}
}

int getfather (int x) {

if ( x == f[x] )
return x;
else  {

int t = f[x];
f[x] = getfather (f[x]);
c[x] = (c[x] + c[t]) % 2;
return f[x];
}
}

int main () {

scanf ("%d", &t);
int x, y;
while (t--) {

scanf ("%d%d", &n, &m);
init();
char s[10];
for (int i = 0; i < m; i++) {

scanf ("%s", s);
if (s[0] == 'D') {

scanf ("%d%d", &x, &y);
int p = getfather(x);
int q = getfather(y);
f[p] = q;
c[p] = (c[y] + c[x] + 1) % 2;
}
else  {

scanf ("%d%d", &x, &y);
int p = getfather(x);
int q = getfather(y);
if (p != q)
printf("Not sure yet.\n");
else if (c[x] == c[y])
printf ("In the same gang.\n");
else
printf ("In different gangs.\n");
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: