4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
#include <cstdio> #include <iostream> #include <cstring> using namespace std ; int f[1005] ; int n, m ; void init() { for(int i = 1 ;i <=n ;i++) { f[i] = i ; } } int getRoot(int v) { if(f[v] == v) return v ; else { f[v] = getRoot(f[v]) ; return f[v] ; } } void merge(int left,int right) { int l = getRoot(left) ; int r = getRoot(right) ; if(l != r) { f[r] = l ; } } int main() { while(scanf("%d%d",&n,&m)!=EOF && n) { init() ; int st,ed ; for(int i = 0 ;i<m ;i++) { scanf("%d%d",&st,&ed) ; merge(st,ed) ; } int sum = 0 ; for(int i = 1;i<=n ;i++) { if(f[i] == i) { sum++ ; } } printf("%d\n",sum-1) ; } return 0 ; }
原文:http://blog.csdn.net/u012566693/article/details/44899611