hdu 1856 More is better

More is better

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 327680/102400 K (Java/Others)
Total Submission(s): 11872    Accepted Submission(s): 4398

Problem 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<stdlib.h>
   2:  #include<stdio.h>
   3:  #include<string.h>
   4:  #include<math.h>
   5:  #define maxn 10000001
   6:  int id[maxn];
   7:  int rank[maxn];//用于记录每棵树的大小
   8:  void init(){
   9:      int i;
  10:      for(i=1;i<=maxn;i++){
  11:          rank[i]=1;
  12:          id[i]=-1;
  13:      }
  14:  }
  15:  int find_root(int x){
  16:      if(id[x]==-1)
  17:          return x;
  18:      return id[x]=find_root(id[x]);
  19:  }
  20:  void Union(int x,int y){
  21:      int rx=find_root(x);
  22:      int ry=find_root(y);
  23:      if(rx==ry)
  24:          return;
  25:      id[ry]=rx;
  26:      rank[rx]=rank[rx]+rank[ry];
  27:  }
  28:  int main(){
  29:      int cases,n,m,i;
  30:      while(scanf("%d",&cases)!=EOF){
  31:          int max=0;
  32:          init();
  33:          while(cases--){
  34:              scanf("%d %d",&n,&m);
  35:              Union(n,m);
  36:          }
  37:          for(i=1;i<=maxn;i++){
  38:              if(id[i]==-1)
  39:                  max=(max>=rank[i]?max:rank[i]);
  40:          }
  41:          printf("%d
",max);
  42:      }
  43:  }
原文地址:https://www.cnblogs.com/ZJUT-jiangnan/p/3588119.html