标签:
Description
Input
Output
Sample Input
Sample Output
Hint
Hint Huge input, scanf is recommended.
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int p[1000]; int find(int x){ return x == p[x] ? x: p[x] = find(p[x]); } void join(int x,int y){ int fx = find(x), fy = find(y); if(fx!=fy){ p[fy] = fx; } } int main() { int N,M,a,b,i,j,ans; int t[1000]; while(~scanf("%d%d",&N,&M)&&N){ for(int i = 1; i <= N; i++) p[i] = i;//排序 memset(t,0,sizeof(t)); for(int i = 1; i <= M ;i++){ scanf("%d%d",&a,&b); join(a,b); } for(int i = 1; i <= N; i++) t[find(i)] = 1;//找有多少个头结点,最后就是头结点总数减一 ans = 0; for(int i = 1; i <= N;i++) if(t[i]) ans++; printf("%d\n",ans-1); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zero-begin/p/4322027.html