Luogu P1536 Village Pass
Idea: Union and search, set the array, initially each set is independent, the value of the array is equal to its subscript, and then each time the value of one number is overwritten by another number, and finally the total number of numbers is output -1 .
Code
#include<bits/stdc++.h>
using namespace std;
int n,m,xa,xb,x,y,i,ans,a[2000];
int find(int s){
int r=s;
while(r!=a[r])r=a[r];
while(s!=r){
int t=s;
s=a[s];
a[t]=r;
}
return r;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(cin>>n>>m){
ans=0;
for(i=1;i<=n;i++)
a[i]=i;
for(i=1;i<=m;i++){
cin>>x>>y;
xa=find(x);
xb=find(y);
if(xa!=xb)
a[xb]=xa;
}
for(i=1;i<=n;i++)
if(a[i]==i)
ans++;
cout<<ans-1<<endl;
}
return 0;
}