zoukankan      html  css  js  c++  java
  • HDU 1232(畅通工程)题解

    以防万一,题目原文和链接均附在文末。那么先是题目分析:

    【一句话题意】

    给定一具有N个节点的图和其边集,求其集合数量。

    【题目分析】

    并查集经典题...其实就是创建好并查集就行了..

    【算法流程】

    于是这里就是放并查集的基本内容的..
    用一个数组的下标来对应节点,值来对应其父节点,并查集英文是Disjoint Sets,就叫DJSet好了XD

    1 int getDjSetPar(int id) { //取得某节点的父节点
    2     if (dj[id]==id) return id;
    3     else return getDjSetPar(dj[id]);
    4 }
    5 
    6 void mergeDjSet(int id1,int id2) { //连接两个集合到一起
    7     dj[getDjSetPar(id1)] = getDjSetPar(id2);
    8 }

    还有一个这题没用到

    void Query(int a,int b) {//判断 a 和 b 是否在同一个集合
       return GetPar(a) == GetPar(b);
    }

    就是这些了...

     1 //Disjoint Sets
     2 
     3 #include <cstdio>
     4 #include <cstdlib>
     5 #include <iostream>
     6 
     7 using namespace std;
     8 
     9 int dj[1061];
    10 
    11 int getDjSetPar(int id) { 
    12     if (dj[id]==id) return id;
    13     else return getDjSetPar(dj[id]);
    14 }
    15 
    16 void mergeDjSet(int id1,int id2) {
    17     dj[getDjSetPar(id1)] = getDjSetPar(id2);
    18 }
    19 
    20 int main() {
    21     int N, M, id1, id2;
    22     while(~scanf("%d",&N)){
    23         if (N==0) break;
    24         else scanf("%d",&M);
    25         for(int i = 1;i<=N;i++) {
    26             dj[i] = i;
    27         }
    28         while(M--) {
    29             scanf("%d%d",&id1,&id2);
    30             if (id1 != getDjSetPar(id2)) mergeDjSet(id1,id2);
    31         }
    32         int counter = 0;
    33         for(int i = 1;i<=N;i++) {
    34             if (getDjSetPar(i) == i) counter++;
    35         }
    36         printf("%d
    ",counter-1);
    37     }
    38 } 
    39 
    40 /*
    41 In 
    42 4 2
    43 1 3
    44 4 3
    45 3 3
    46 1 2
    47 1 3
    48 2 3
    49 5 2
    50 1 2
    51 3 5
    52 999 0
    53 0
    54 
    55 Out
    56 1
    57 0
    58 2
    59 998
    60 */


    题目链接:畅通工程(HDU 1232)

    题目属性:并查集

    相关题目:1198 1213 1272

    题目原文:
    【Desc】某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
    【In】测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。
    注意:两个城市之间可以有多条道路相通,也就是说
    3 3
    1 2
    1 2
    2 1
    这种输入也是合法的
    当N为0时,输入结束,该用例不被处理。
    【Out】对每个测试用例,在1行里输出最少还需要建设的道路数目。
    【SampIn/Out】参见代码下方的注释。

  • 相关阅读:
    mysql查看锁表情况
    利用xtrabackup备份mysql数据库
    /proc/sys/vm/参数
    linux的sysctl基本配置
    python计算apache总内存
    ip_conntrack table full dropping packet错误的解决方法
    apachetop 实时监控apache指定日志
    mysql大表myisam的导入
    编译安装php5.5和php-fpm
    tshark 抓包分析
  • 原文地址:https://www.cnblogs.com/blumia/p/hdu1232.html
Copyright © 2011-2022 走看看