Description
Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.
Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang's selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.Input
The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)Output
The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.Sample Input
41 23 45 61 641 23 45 67 8Sample Output
42
源代码+注释#include<cstdio> #include<algorithm> using namespace std; const int Max=1e6+10; int par[Max]; int num[Max];//创建一个数组记录分支个数 int n; int MAX; void init(int n) { for(int i=1;i<Max;i++) { par[i]=i; num[i]=1;//单独的一个点代表一个分支所以初始值为1 } } int find(int x) { int p=x; while(x!=par[x]) x=par[x]; while(par[p]!=x) { int j=par[p]; par[p]=x; p=j; } return par[x]; } void unite(int a,int b) { int fa=find(a); int fb=find(b); //printf("fa=%d,fb=%d\n",fa,fb); if(fb!=fa) { par[fa]=fb; num[fb]+=num[fa];//因为fa合并到fb上所以fb的分支就等于他本来的分支加上fa的分支 if(num[fb]>MAX)//寻找拥有最大分支的树并记录它的分支个数 MAX=num[fb]; //printf("MAX=%d,num[fa]=%d\n",MAX,num[fa]); } } int main() { while(scanf("%d",&n)!=EOF) { MAX=1; init(n); int a,b; for(int i=0;i<n;i++) { scanf("%d%d",&a,&b); unite(a,b); } printf("%d\n",MAX); } return 0; }