2019_GDUT_ newborn thematic map on H- Smooth Traffic Project

Source HDU1232

Title:
province town traffic surveys, existing urban roads to get 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

Ideas: disjoint-set, the required number of road construction between the various groups that is the answer

Code:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#define INF 0x3f3f3f3f
using namespace std;
int N,pre[1010];
int find(int x)
{
	while (pre[x]!=x)
	x=pre[x];
	return x;
}

int main()
{
	int A,B,n,m;
	scanf("%d",&n);
	while (n!=0)
	{
		for (int i=1;i<=n;i++)
		pre[i]=i;
		scanf("%d",&m);
		for (int i=1;i<=m;i++)
		{
			scanf("%d%d",&A,&B);
			pre[find(A)]=find(B);
		}
		int ans=0;
		for (int i=1;i<=n;i++)
		if (pre[i]==i) ans++;
		if (ans)
		printf("%d\n",ans-1);
		else printf("0\n");
		scanf("%d",&n);
	}
	return 0;
}

Published 33 original articles · won praise 0 · Views 1943

Guess you like

Origin blog.csdn.net/qq_39581539/article/details/104811229