您的位置:首页 > 其它

并查集 POJ 1988

2015-04-05 23:51 232 查看
#include <cstdio>
#define N 30010
int pa
; //parent
int siz_tree
; //size of tree
int d
; //dist between node and root
int Find(int x)
{
if(pa[x] == x) return x;
int t = pa[x];
pa[x] = Find(pa[x]);
d[x] += d[t];
return pa[x];
}
void Union(int x, int y)
{
x = Find(x), y = Find(y);
pa[x] = y;
d[x] += siz_tree[y];
siz_tree[y] += siz_tree[x];
siz_tree[x] = 0;
}
int main()
{
int p;
while(~scanf("%d", &p))
{
for(int i = 0; i < N; i++) pa[i] = i, siz_tree[i] = 1, d[i] = 0;

char c;
int x, y;

for(int i = 0; i < p; i++) {
while(1) {
c = getchar();
if(c == 'M' || c == 'C') break;
}
if(c == 'M') {
scanf("%d%d", &x, &y);
Union(x, y);
}
else {
scanf("%d", &x);
Find(x);
printf("%d\n", d[x]);
}
}
}
return 0;
}


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