Smooth Traffic Project HDU - 1232 ----- disjoint-set

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.
The Input the Sample
. 4 2
. 1. 3
. 4. 3
. 3. 3
. 1 2
. 1. 3
2. 3
. 5 2
. 1 2
. 3. 5
999 0
0
the Sample the Output
. 1
0
2
998

Huge input, scanf is recommended.
Hint
Hint

Analysis: There are a number n connected components, each have an effective combined -1
final answer ans-1.



#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=1e5+100;
int fa[N];
int n,m,a,b,x,y;
int find(int x)
{
	if(fa[x]!=x) return fa[x]=find(fa[x]);
	return fa[x];
}
int build(int a,int b)
{
	a=find(a);b=find(b);
	if(a!=b)
	{
		fa[a]=b;
		return 1;
	 } 
	 return 0;
}
int main()
{
	while(~scanf("%d",&n)&&n!=0)
	{
		scanf("%d",&m);
		for(int i=0;i<=n;i++ ) fa[i]=i;
		int ans=n;
		while(m--)
		{
			scanf("%d %d",&a,&b);
			ans-=build(a,b); 
		}
		cout<<ans-1<<endl; 
	 } 
}

Published 309 original articles · won praise 6 · views 5275

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/104066272