首页 > 其他 > 详细

hdu 2120

时间:2017-08-21 15:30:23      阅读:184      评论:0      收藏:0      [点我收藏+]

题意:求连通块中有多少个环。

题解:如果两数的祖先相同则总数加1,否则合并。

 

代码:

#include <cstdio>
int pre[2100],sum[2100],tot;
int
find(int x){
    int
r = x;
    while
(pre[r] != r){
        r = pre[r];
    }

    int
i = x, j;
    while
(i != r){
        j = pre[i];
        pre[i] = r;
        i = j;
    }

    return
r;
}

void
join(int x,int y){
    int
fx=find(x);
    int
fy=find(y);
    if
(fx!=fy)
        pre[fy]=fx;
    else
tot++;
}


int
main(){
    int
n,m;
    while
(scanf("%d%d",&n,&m)!=EOF){
        int
a,b;
        for
(int i = 0; i < n; i++)
        {

            pre[i] = i;
        }

        tot=0;
        for
(int i=0;i<m;i++){
            scanf("%d%d",&a,&b);
            join(a,b);
        }

        printf("%d\n",tot);
    }

    return
0;
}

hdu 2120

原文:http://www.cnblogs.com/LMissher/p/7404407.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!