并查集
畅通工程
#include<iostream> #include<cstdio> using namespace std; int par[1010]; int find(int x) { if(par[x] != x) { par[x] = find( par[x] ); } return par[x]; } int unio(int x,int y) { int a_root = find(x); int b_root = find(y); if(a_root != b_root) par[a_root] = b_root ; return 1; } int main() { int n,m; while(~scanf("%d",&n)&&n) { scanf("%d",&m); for(int i=1;i<=n;++i) par[i]=i; int begin,end; int cnt = 0; for(int i=0;i<m;++i) { scanf("%d%d",&begin,&end); unio(begin,end); } for(int i=1;i<=n;++i) if(par[i] == i) ++cnt; printf("%d\n",cnt-1); } return 0; }