zoukankan      html  css  js  c++  java
  • hdu1232 并查集

    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
    ",num-1);
    
        }
    
        return 0;
    }
    View Code
  • 相关阅读:
    课后作业
    课后作业
    课后作业3
    课后作业
    课后作业
    课后作业
    java 加减法2
    java 出计算题
    Java web 登录界面
    构建之法读后感
  • 原文地址:https://www.cnblogs.com/sbfhy/p/5745942.html
Copyright © 2011-2022 走看看