Smooth Traffic Project (disjoint-set)

Problem Description
province 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

 

#include <bits / STDC ++ H.>
 the using  namespace STD; 
typedef Long  Long LL;
 int A [ 1000 + . 5 ], n-, K, L, R & lt;
 int Find ( int T) 
{ 
    return T == A [T]? T: Find (A [T]);      //// condensing point: repeatedly up inquiry, inquiry was assigned to the root 
}
 void Solve ( int LL, int RR) 
{ 
    Find (LL) !? = Find (RR) A [Find (LL)] = Find (RR): 0 ;    // the root node update, it may also be referred to a set of combined or added 
}
 int main () 
{ 
    the while (n-CIN >> >> K &&n)
    {
        for(int i=1;i<=n;i++) a[i]=i;
        for(int i=1;i<=k;i++)
        {
            cin>>l>>r;
            solve(l,r);
        }
        int ans = 0;
        for(int i=1;i<=n;i++)
            if(i!=a[i])
                ans++;
        cout<<n-1-ans<<endl;
    }
} 

 

Guess you like

Origin www.cnblogs.com/Shallow-dream/p/11426021.html