HDU 1232 Unblocked Engineering

                                            Smooth project

A province investigates urban traffic conditions and obtains a statistical table of existing urban roads, which lists the cities and towns directly connected by each road. The goal of the provincial government's "unblocking project" is to enable traffic between any two towns in the province (but not necessarily directly connected by road, as long as they are accessible by road). How many roads will need to be built at least?  
Input test input contains several test cases. The first line of each test case gives two positive integers, which are the number of towns N ( < 1000 ) and the number of roads M; the subsequent M lines correspond to M roads, and each line gives a pair of positive integers, which are the The number of two towns directly connected by a road. For simplicity, towns are numbered from 1 to N.  
Note: There can be multiple roads between two cities, that is to say,   the input of
3 3  
1 2  
1 2  
2 1  
is also legal.  
When N is 0, the input ends, and this use case is not processed.  
Output For each test case, output the minimum number of roads that need to be built in one line.  
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.
Hint
 
 

Hint


HDU actually has two unblocked projects (Khan
The topic is very simple. My idea is that if a road is merged with a parallel search set, then the road that needs to be repaired is reduced by one.

code show as below:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<string>
#include<queue>
#include<vector>
#include<stack>
#include<list>
using namespace std;
struct node
{
    int u,v;

} s[1005];
int pre[1005];
int Find(int x)
{
    return x==pre[x]?x:pre[x]=Find(pre[x]);
}

int main()
{
    int n,m,i;
    while(scanf("%d",&m),m)
    {
        scanf("%d",&n);
        int k=m-1;
        for(i=0; i<=m; i++)
            pre[i]=i;
        for(i=0; i<n; i++)
            scanf("%d %d",&s[i].u,&s[i].v);
        for(i=0; i<n; i++)
        {
            int fx=Find(s[i].u),fy=Find(s[i].v);
            if(fx!=fy)
            {
                pre[fx]=fy;
                k--;
            }
        }
        cout<<k<<endl;

    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326304182&siteId=291194637