#P1536. 村村通

村村通

Description

A city surveyed its urban transportation and obtained a current list of roads between towns. The list enumerates which pairs of towns are directly connected by a road. The goal of the city’s "Village-to-Village Connectivity" project is to ensure that any two towns in the city can reach each other (there does not have to be a direct road between them, as long as they are mutually reachable). Please compute the minimum number of additional roads that still need to be built.

Input Format

The input contains multiple test cases. For each test case, the first line gives two positive integers separated by a space, the number of towns nn and the number of roads mm. The following mm lines describe the mm roads; each line gives a pair of positive integers separated by a space, which are the labels of the two towns directly connected by that road. For simplicity, towns are labeled from 11 to nn.

Note: multiple roads may exist between the same pair of towns.

At the end of the input, there is a line containing a single integer 00, which marks the end of the testdata.

Output Format

For each test case, output a single integer on its own line: the minimum number of additional roads required.

4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0

1
0
2
998

Hint

Constraints

For 100%100\% of the testdata, 1n<10001 \le n < 1000.

Translated by ChatGPT 5