【并查集】HDOJ 1856 More is better

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

4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8

Sample Output

4
2

Hint

 

A and B are friends(direct or indirect), B and C are friends(direct or indirect), then A and C are also friends(indirect). In the first sample {1,2,5,6} is the result. In the second sample {1,2},{3,4},{5,6},{7,8} are four kinds of answers.



并查集应用,求每个连通子图的节点个数。

  1. #include<iostream>  
  2. #include<stdio.h>  
  3. #include<string.h>  
  4. #define MAXN 10000010  
  5. using namespace std;  
  6. int Tree[MAXN];  
  7. int sum[MAXN];  
  8. int n;  
  9. int findRoot(int x){  
  10.     if(Tree[x]==-1)  
  11.         return x;  
  12.     else{  
  13.         int tmp=findRoot(Tree[x]);  
  14.         Tree[x]=tmp;  
  15.         return tmp;  
  16.     }  
  17. }  
  18. int main(){  
  19.     int a,b;  
  20.     while(scanf("%d",&n)!=EOF&&n!=0){  
  21.         //memset(sum,1,sizeof(sum));  memset失效了是什么鬼  
  22.         for(int i=0;i<MAXN;i++){  
  23.             sum[i]=1;  
  24.         }  
  25.         memset(Tree,-1,sizeof(Tree));  
  26.         for(int i=0;i<n;i++){  
  27.             scanf("%d %d",&a,&b);  
  28.             int fa=findRoot(a);  
  29.             int fb=findRoot(b);  
  30.             if(fa!=fb){  
  31.                 Tree[fa]=fb;  
  32.                 sum[fb]+=sum[fa];  
  33.             }  
  34.         }  
  35.         int ans=1;  
  36.         for(int i=1;i<MAXN;i++){  
  37.             if(Tree[i]==-1&&ans<sum[i]){  
  38.                 ans=sum[i];  
  39.             }  
  40.         }  
  41.         printf("%d\n",ans);  
  42.       
  43.     }  
  44.       
  45. }  
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页