D - Smooth Traffic Project

A provincial survey of urban traffic, urban roads to get existing tables, the table lists the cities and towns each road directly connected. Target provincial government "Smooth Traffic Project" is to make the province between any two towns can implement traffic (but not necessarily directly connected to the road, as long as you can reach each other indirectly through road). Minimum asked how many roads also need to build?

 

Input

Test input contains several test cases. Each test case is given row of the first two positive integers, are the number of towns N (<1000) and road number M; M rows corresponding to the next M path, each row is given a pair of positive integers, respectively, the number two towns in direct communication path. For simplicity, the town numbered from 1 to N.
Note: number of roads may be communicated between the two cities, ie
. 3. 3
. 1 2
. 1 2
2. 1
This input is valid
when N is 0, an input end, the use cases are not processed.

 

Output

For each test case, the number of roads in at least one line in the output needed construction.


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

 

Huge input, scanf is recommended.

 

Code

 

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 100000+10;
 5 int fa[maxn];
 6 void init(int n)//初始化 
 7 {
 8     for(int i=1;i<=n;i++){
 9         fa[i]=i;
10     }
11 }
12 int findfa(int a)
13 {
14     if(fa[a]!=a) fa[a]=findfa(fa[a]);
15     return fa[a];
16 }//寻找祖宗节点 
17 void unionn(int a,int b)
18 {
19     int faa=findfa(a);
20     int fab=findfa(b);
21     if(faa!=fab){
22         fa[faa]=fab;
23     }
24 }//联通两个节点的祖宗节点 
25 int main(void)
26 { 
27     int n,m,a,b;
28     while(scanf("%d",&n)){
29         if(n==0) break;
30         scanf("%d",&m); 
31         init(n);
32         for(int i=0;i<m;i++){
33             scanf("%d%d",&a,&b);
34             unionn(a,b);
35         }
36         int ans=0;
37         for(int i=1;i<=n;i++){
38             if(fa[i]==i) ans++; 
39         }
40         ans--;
41         printf("%d\n",ans);
42     }
43     return 0;
44 }

 

Guess you like

Origin www.cnblogs.com/-happy-/p/12272854.html