Title Description:
A province investigates urban traffic conditions and obtains statistical tables of existing urban roads, which list the towns where each road is directly connected. The goal of the provincial government's "unblocked project" is to enable traffic to be achieved between any two towns in the province (but not necessarily directly connected to each other, as long as they can be reached indirectly through the road). How many roads must be built at least. Input:
The test input contains several test cases. The 1th line of each test case gives two positive integers, namely the number of towns N (< 1000) and the number of roads m, followed by M-lines, each with a pair of positive integers, the number of two towns directly connected to the road. For simplicity, towns are numbered from 1 to N.
Note: There can be more than one road connection between two cities, which means
3 3
1 2
1 2
2 1
This type of input is also legal.
When n is 0 o'clock, the input ends and the use case is not processed. Output:
For each test case, the minimum number of roads required to be built in line 1 is output. Sample Input:
4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0
Sample output:
1
0
2
998
A typical one and look up the topic
Besides,
Find (x) function
int find (int x) {
if (a[x]==x)
return x;
Return X=find (A[x]);
}
Written in such a way to save time, before doing the Blue Bridge Cup over the years topic ... Dead at this point.
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
int a[1000+5];
int find (int x) {
if (a[x]==x)
return x;
Return X=find (A[x]);
}
void Add (int x,int y) {
x=find (x);
Y=find (y);
if (x!=y) a[x]=y;
}
int main () {
int n,m;
while (cin>>n>>m) {
if (n==0) break ;
for (int i=1;i<=n;i++) a[i]=i;
for (int i=0;i<m;i++) {
int A, b;
cin>>a>>b;
Add (Find (a), find (b));
}
int fz[1000+5]={0};
for (int i=1;i<=n;i++) {
fz[find (i)]++;
}
int sum=0;
for (int i=1;i<=n;i++) {
if (fz[i]>0)
sum++;
}
cout<<sum-1<<endl;
}
return 0;
}