畅通工程(并查集)
还是寻求father[i]=i代表几个集合,还有初始化MAXN不能有等于,Make_seth函数再次忘记写了
#include<stdio.h> const int MAXN=1010; int father[MAXN],rank[MAXN]; void Make_set() { for(int i=1;i<MAXN;i++) { father[i]=i; rank[i]=0; } } int Find(int x) { int r=x; while(r!=father[r]) { r=father[r]; } if(r!=x) father[x]=r; return father[x]; } void Union(int x,int y) { if(x==y) return ; if(rank[x]>rank[y]) { father[y]=x; } else { if(rank[x]==rank[y]) { rank[y]++; } father[x]=y; } } int main() { int n,m,i,a,b; while(scanf("%d",&n)) { if(n==0) break; scanf("%d",&m); Make_set(); for(i=0;i<m;i++) { scanf("%d%d",&a,&b); int x=Find(a); int y=Find(b); Union(x,y); } int total=0; for(i=1;i<=n;i++) { // printf("%d\n",father[i]); if(father[i]==i) total++; } printf("%d\n",total-1); } return 0; }