机试练习04:hdu1232——畅通工程

一、题解方法

使用方法:并查集搜索。

主要思想:初始状态下,N个城镇需要修建N-1条道路。每增加一条道路,判断道路两端点是不是在同一个集合中。若在同一集合中,这条路就是没有意义的;若不在同一集合中,则要修建的道路数-1。

二、题解代码

 1 #include <iostream>
 2 #include "stdio.h"
 3 #include "stdlib.h"
 4 
 5 
 6 using namespace std;
 7 
 8 int a[1010];
 9 
10 int find(int x)
11 {
12     if(x != a[x])
13         a[x] = find(a[x]);
14     return a[x];
15 }
16 
17 int main()
18 {
19     int n, m;
20     int i, j;
21     int x, y;
22     scanf("%d", &n);
23     while(n)
24     {
25         scanf("%d", &m);
26         for(i = 0; i <= n; i++)
27         {
28             a[i] = i;
29         }
30         j = n - 1;
31         for(i = 0; i < m; i++)
32         {
33             
34             scanf("%d%d", &x, &y);
35             x = find(x);
36             y = find(y);
37             if(x != y)
38             {
39                 a[y] = x;
40                 j--;
41             }
42         }
43         printf("%d\n", j);
44         scanf("%d", &n);
45         
46     }
47     return 0;
48 }

 

posted @ 2018-04-09 19:52  Alyssa_young  阅读(174)  评论(0编辑  收藏  举报