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

hdu1232 并查集

时间:2016-08-07 13:39:18      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

1、 hdu1232   

2、链接:http://acm.hdu.edu.cn/showproblem.php?pid=1232

3、总结:简单并查集

技术分享
#include<iostream>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
#include<cstdio>
using namespace std;
#define LL long long
#define INF 0x3f3f3f3f

const int N=1010;
int father[N];

/*    //未优化的查找
int findn(int n)
{
    while(father[n]!=n){
        n=father[n];
    }
    return n;
}   */

int findn(int n)
{
    int x=n;
    while(father[x]!=x){
        x=father[x];
    }

    int i=n,j;
    while(father[i]!=x)    //优化
    {
        j=father[i];
        father[i]=x;
        i=j;
    }
    return x;
}

int main()
{
    int n,m;
    while(scanf("%d",&n)!=EOF&&n)
    {
        //初始化
        for(int i=1;i<=n;i++)
            father[i]=i;

        scanf("%d",&m);
        int x,y;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&x,&y);
            
            //合并
            int tempx=findn(x);
            int tempy=findn(y);
            if(tempx!=tempy)father[tempx]=tempy;

        }

        //找出连通分量的个数,减一
        int num=0;
        for(int i=1;i<=n;i++)
        {
            if(father[i]==i)num++;
        }
        printf("%d\n",num-1);

    }

    return 0;
}
View Code

 

hdu1232 并查集

标签:

原文地址:http://www.cnblogs.com/sbfhy/p/5745942.html

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