(CBT) high-speed rail network

High-speed rail network

description:

Nation-building high-speed rail network, which consists of a number of high-speed rail line connecting the city. Existing high-speed rail construction could be classified as a statistical table, the table lists each of the two cities a high-speed rail line directly connected. Construction is to target countries can achieve high-speed rail traffic between the two cities per country (but not necessarily directly connected to high-speed rail line, as long as indirectly through high-speed rail line up to). Ask the minimum number of high-speed rail line would also like to build?

Enter a description:

Test line 1 are given two positive integers, respectively, the number of cities is N (<1000) and the number of existing high-speed rail line M. M then M rows corresponding to high-speed rail lines, each line is given a pair of positive integers, respectively the two cities article directly connected high-speed line number. For simplicity, the city numbered from 1 to N.

Output Description:

On the line of output also the least number of high-speed rail lines need to build.

Sample input:

9 8

1 2

1 3

2 4

3 4

5 7

5 6

6 7

8 9

Sample output:

2

To achieve prompt:

The number of the real problem for the sake of reducing a communication component, available depth-first or breadth-first search to solve, can also be solved MFSet.

#include<stdio.h>
#include<stdlib.h>
int vset[100];
int findset(int x)
{
	while (vset[x] != 0)
		x = vset[x];
	return x;
}
int main ()
{
	int m, n, i, a, b, va, vb, count;
	scanf("%d", &n);
	for (i = 0; i < n; i++)
		vset[i] = 0;
	scanf("%d", &m);
	for (i = 0; i < m; i++)
	{
		scanf("%d %d", &a, &b);
		va = findset(a);
		vb = findset(b);
		if (va != vb)
			vset[va] = vb;
	}
	count = 0;
	for (i = 0; i < n; i++)
	{
		if (vset[i] == 0)
			count++;
	}
	printf("%d", count-1);
	return 0; 

}

  

 

Guess you like

Origin www.cnblogs.com/KIROsola/p/11909403.html