4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
1 0 2 998Huge input, scanf is recommended.HintHint
#include<cstdio> #include<iostream> using namespace std; int father[1001]; void init() { for(int i=1;i<=1001;i++) father[i]=i; } int Find(int x) { return x==father[x]?x:father[x]=Find(father[x]); } void Union(int x,int y) { int x1=Find(x); int y1=Find(y); if(x1!=y1) father[y1]=x1; } int main() { int n,m; while(scanf("%d",&n)!=EOF) { if(!n) return 0; cin>>m; int c=0; init(); int a,b; while(m--) { cin>>a>>b; Union(a,b); } for(int i=1;i<=n;i++) if(father[i]==i) c++; cout<<c-1<<endl; } return 0; }
原文:http://blog.csdn.net/novak_djokovic/article/details/44784179