看这个博主讲的并查集入门看懂的,很有趣,一看就懂 传送门
#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn=1005;
const int inf=0x3f3f3f3f;
int n,m,f[maxn];
int a[maxn];
int unionsearch(int root){
int son=root;
while(f[root]!=root){//祖先
root=f[root];
}
while(son!=root){
son=f[son];
f[son]=root;
}
return root;
}
int main()
{
int a,b,root1,root2;
while(scanf("%d%d",&n,&m),n){
int total=n-1;//初始化,若这个地方一条路都没修过,则最少需要 n-1条
for(int i=1;i<=n;i++){
f[i]=i;
}
for(int i=0;i<m;i++){
scanf("%d%d",&a,&b);
root1=unionsearch(a);
root2=unionsearch(b);
if(root1!=root2){//表示新修的路a,b。若a,b是完全不相连的两条路,即根节点不一样,表示这条路已经修了,则需要修的路total-1。
f[root1]=root2;
total--;
}
}
printf("%d\n",total);
}
return 0;
}
还有一种输出方法,因为如果f[i]==i,表示该条路没有和其他路相连接,就要修一条路将其他路连接起来,因为本来就有一个根节点不需要再连接其他的根节点了,所以ans-1。
int ans=0;
for(int i=1;i<=n;i++){
if(f[i]==i)
ans++;
}
printf("%d\n",ans-1);