题目链接: https://ac.nowcoder.com/acm/problem/14685
并查集模板题
关于并查集 https://blog.csdn.net/lanyanzhiji123asd/article/details/88072561
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<string>
using namespace std;
int pre[100005];
int find(int n)
{
if(pre[n]==n)
return n;
pre[n]=find(pre[n]);
return pre[n];
}
int main()
{
int n,m,i,a,b;
while(cin>>n>>m)
{
int cnt=n-1;
for(i=0;i<=n;i++)
pre[i]=i;
for(i=0;i<m;i++)
{
cin>>a>>b;
int xx=find(a);
int yy=find(b);
if(xx!=yy)
{
cnt--;
pre[yy]=xx;
}
}
cout<<cnt<<endl;
}
}