Three Questions on the topic _ winter training solution _H - Smooth Traffic Project

topic

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.

Subject to the effect

There are n points, m road, plus a couple of choices and asked to make a minimum of n points connected twenty-two

answer

Disjoint-set template

Code

#include <iostream>

using namespace std;
const int N = 1010;
long long n,m;
int p[N];
void init()
{
	for(int i = 1; i<=n; i ++)
	p[i] = i; 
}
int find(int x)
{
	if(x == p[x])return x;
	return p[x] = find(p[x]);
}
int main()
{
	while(scanf("%lld",&n)&&n)
	{
		scanf("%lld",&m);
		init();
		for(long long i = 1; i <= m; i ++)
		{
			int a,b;
			scanf("%d%d",&a,&b);
			if(find(a) == find(b))continue;
			else if(find(a) > find(b))swap(a,b); //保证find(a)<=a
			p[find(b)] = find(a);
		}
		int cnt = 0;
		for(int i = 2; i <= n; i ++)
		{
			if(1 != find(i))
			{
				cnt ++;
				p[find(i)] = 1;
			}
		}
		printf("%d\n",cnt);
	}
	return 0;
}
Published 13 original articles · won praise 0 · Views 131

Guess you like

Origin blog.csdn.net/m0_46185124/article/details/103979428