ACM HDU Unblocked 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 on 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.
#include<iostream>
#include<cstdio>
using namespace std;
int f[1005];
int find_out(int x){
	while(f[x]!=x)
	x=f[x];
	return x;
}
void combine(int x,int y){
	you gave, tb;
	ta=find_out(x);
	tb=find_out(y);
	if(ta!=tb)
	f [ta] = tb;
}
int find_ans(int n){
	int sum=0;
	for(int i=1;i<=n;i++){
		if(f[i]==i) find the root node
		sum++;
	}
	return sum;
}
int main(){
	int n,m,a,b;
	while(~scanf("%d",&n)){
		if(!n)
		break;
		for(int i=1;i<=n;i++)
		f[i]=i; initialize the parent node array
		scanf("%d",&m);
		for(int i=1;i<=m;i++){
			scanf("%d%d",&a,&b);
			combine(a,b);
		}
		printf("%d\n",find_ans(n)-1);
	}
	return 0;
}

Guess you like

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