zoukankan      html  css  js  c++  java
  • HDU1232 畅通工程

    Problem Description
    某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
     
    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
     
     
    正解:并查集
    解题报告:
      并查集裸题。
     
     1 //It is made by jump~
     2 #include <iostream>
     3 #include <cstdlib>
     4 #include <cstring>
     5 #include <cstdio>
     6 #include <cmath>
     7 #include <algorithm>
     8 #include <ctime>
     9 #include <vector>
    10 #include <queue>
    11 #include <map>
    12 #include <set>
    13 #ifdef WIN32   
    14 #define OT "%I64d"
    15 #else
    16 #define OT "%lld"
    17 #endif
    18 using namespace std;
    19 typedef long long LL;
    20 const int MAXN = 1011;
    21 int n,m,cnt;
    22 int father[MAXN];
    23 
    24 inline int getint()
    25 {
    26        int w=0,q=0;
    27        char c=getchar();
    28        while((c<'0' || c>'9') && c!='-') c=getchar();
    29        if (c=='-')  q=1, c=getchar();
    30        while (c>='0' && c<='9') w=w*10+c-'0', c=getchar();
    31        return q ? -w : w;
    32 }
    33 
    34 inline int find(int x){
    35     if(father[x]!=x) father[x]=find(father[x]);
    36     return father[x];
    37 }
    38 
    39 inline void hebing(int x,int y){
    40     int r1=find(x),r2=find(y);
    41     if(r1!=r2) father[r2]=r1;    
    42 }
    43 
    44 inline void work(){
    45     while(1) {
    46     n=getint(); if(n==0) break;
    47     m=getint(); int x,y; cnt=0;
    48     for(int i=1;i<=n;i++) father[i]=i;
    49     for(int i=1;i<=m;i++)  x=getint(),y=getint(),hebing(x,y);
    50     for(int i=1;i<=n;i++) if(father[i]==i) cnt++;
    51     printf("%d
    ",cnt-1);
    52     }
    53 }
    54 
    55 int main()
    56 {
    57   work();
    58   return 0;
    59 }
     
     
     
  • 相关阅读:
    微软面试题_中文字符串转换为数字
    微软面试题_3个字母的组合
    LeetCode Notes_#1031_两个非重叠子数组的最大和
    剑指Offer_#57-II_和为 s 的连续正数序列
    LeetCode Notes_#560 和为k的子数组
    LeetCode Notes_#84 柱状图中最大的矩形
    LeetCode Notes_#221 最大正方形
    LeetCode Notes_#146 LRU缓存机制
    码云团队开发项目拉取与推送
    vue父子组件的双向绑定
  • 原文地址:https://www.cnblogs.com/ljh2000-jump/p/5764422.html
Copyright © 2011-2022 走看看