标签:
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<iostream> #include<stdio.h> using namespace std; int pre[1000]; int find(int r) { while(r!=pre[r]) r=pre[r]; return r; } void join(int a,int b) { int x,y; x=find(a); y=find(b); if(x!=y) pre[y]=x; } int main() { int N,M,a,b,ans,i; while(scanf("%d",&N) && N) { scanf("%d",&M); for(i=1;i<=N;i++) pre[i]=i; ans=0; for(i=1;i<=M;i++) { scanf("%d%d",&a,&b); join(a,b); } for(i=1;i<=N;i++) { if(pre[i]==i) ans++; } printf("%d\n",ans-1); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/zuguodexiaoguoabc/article/details/48084925