• HDU 1243 畅通project 并査集


    Total Submission(s): 31033    Accepted Submission(s): 16313


    Problem Description
    某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通project”的目标是使全省不论什么两个城镇间都能够实现交通(但不一定有直接的道路相连,仅仅要互相间接通过道路可达就可以)。问最少还须要建设多少条道路?
     

    Input
    測试输入包括若干測试用例。每一个測试用例的第1行给出两个正整数,各自是城镇数目N ( < 1000 )和道路数目M;随后的M行相应M条道路,每行给出一对正整数,各自是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。
    注意:两个城市之间能够有多条道路相通,也就是说
    3 3
    1 2
    1 2
    2 1
    这样的输入也是合法的
    当N为0时,输入结束,该用例不被处理。
     

    Output
    对每一个測试用例,在1行里输出最少还须要建设的道路数目。
     

    Sample Input
    4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
     

    Sample Output
    1 0 2 998
    Hint
    Hint



    水题,就是把有关系的联系在一起,不解释



    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    #define N 10005
    
    int father[N];
    
    int cha(int x)
    {
        if(x!=father[x])
            father[x]=cha(father[x]);
        return father[x];
    }
    
    int main()
    {
        int i,n,m;
        while(scanf("%d",&n),n)
        {
            scanf("%d",&m);
    
            for(i=1;i<=n;i++)
                father[i]=i;
    
            int x,y;
    
            while(m--)
            {
                scanf("%d%d",&x,&y);
                int xx=cha(x);
                int yy=cha(y);
                father[xx]=yy;
            }
    
    
            int ans=-1;
            for(i=1;i<=n;i++)
                if(father[i]==i)
                ans++;
    
            printf("%d
    ",ans);
        }
        return 0;
    }
    


  • 相关阅读:
    #include <boost/shared_array.hpp>
    #include <boost/shared_ptr.hpp>
    #include <boost/scoped_array.hpp>
    df命令
    telnet命令
    sort 命令
    苏宁大数据面试题
    hive严格模式
    k-means伪代码
    vim编辑器
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4239890.html
Copyright © 2020-2023  润新知