码迷,mamicode.com
首页 > 其他好文 > 详细

并查集 POJ 1988

时间:2015-04-06 00:45:06      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:

#include <cstdio>
#define N 30010
int pa[N]; //parent
int siz_tree[N]; //size of tree
int d[N]; //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;
}

  

并查集 POJ 1988

标签:

原文地址:http://www.cnblogs.com/sunus/p/4395129.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!