参考:https://blog.csdn.net/oliver233/article/details/70162173
带路径压缩模板:
1 #include<stdio.h> 2 int father[1005]; 3 int Find(int x) 4 { 5 6 if(x!=father[x])//注意这里是if不是while! 7 father[x]=Find(father[x]); 8 return father[x]; 9 } 10 void Combine(int a,int b) 11 { 12 int fa=Find(a); 13 int fb=Find(b); 14 if(fa!=fb) 15 { 16 father[fa]=fb; 17 } 18 } 19 int main() 20 { 21 // freopen("in.txt","r",stdin); 22 int n,m; 23 int i; 24 int a,b; 25 while(~scanf("%d",&n)) 26 { 27 if(n==0) 28 break; 29 scanf("%d",&m); 30 int sum=0; 31 for(i=1;i<=n;i++) 32 father[i]=i; 33 for(i=0;i<m;i++) 34 { 35 scanf("%d%d",&a,&b); 36 Combine(a,b); 37 } 38 for(i=1;i<=n;i++) 39 { 40 if(father[i]==i) 41 sum++; 42 } 43 printf("%d ",sum-1); 44 } 45 return 0; 46 }