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.
4 1 2 3 4 5 6 1 6 4 1 2 3 4 5 6 7 8
4 2 -------------------------------------------------简单的并查集;求的是,最大树中的元素个数;#include<stdio.h> #include<stdlib.h> #include<string.h> int cmp(const void *a,const void *b) { return *(int *)b - *(int *)a; } int pre[20000000]; int size[20000000]; int f(int n) { if(pre[n]==n) return n; else pre[n] = f(pre[n]); } int main() { int n,a,b,x,y,i; while(scanf("%d",&n)!=EOF) { //if(n==0)//还有就是这里当n=0时,要输出1,其实不要也行, //{ 因为我把size数组初始化为1,所以当n为0时,中间的两个for都不会执行,排序之后,输出结果1,正确 // printf("1\n"); // continue; //} for(i=0;i<=2*n;i++) { pre[i] = i; size[i] = 1; } for(i=0;i<n;i++) { scanf("%d %d",&a,&b); x = f(a); y = f(b); if(x!=y) { pre[y]=x; size[x] += size[y];// 刚才把这句话写在if外面了,结果错了; //应该是 当两者祖先不同 ,合并时size的大小才更新 } } qsort(size,2*n,sizeof(size[0]),cmp); printf("%d\n",size[0]);
} return 0; }