Disjoint-set -D - Smooth Traffic Project

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, output the minimum number of roads also need to build in a row.
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.
 
 1 #include<iostream>
 2 using namespace std;
 3 
 4 int load[1010];
 5 void init(){
 6     for(int i=0;i<1010;i++)
 7         load[i] = i;
 8 }
 9 
10 int find(int x){
11     return x==load[x]? x : load[x]=find(load[x]);
12 }
13 
14 void load_union(int x,int y){
15     int fx = find(x);
16     int fy = find(y);
17     load[fy] = fx;
18 }
19 
20 int main(){
21     int n;
22     while(scanf("%d",&n)!=EOF){
23         if(n==0) break;
24         init();
25         int m,x,y,num=0;
26         scanf("%d",&m);
27         for(int i=0;i<m;i++){
28             scanf("%d %d",&x,&y);
29             if(find(x)!=find(y))    load_union(x,y);
30         }
31         for(int i=1;i<=n;i++)
32             if(i==load[i])
33                 num++;
34         printf("%d\n",num-1);
35     }
36 }
 

 

 

Guess you like

Origin www.cnblogs.com/0424lrn/p/12220573.html