zoukankan      html  css  js  c++  java
  • HDU 1856 More is better(并查集找最大集合)

    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. 

    InputThe 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)OutputThe 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<stdio.h>
     2 #include<string.h>
     3 #include<algorithm>
     4 #include<iostream>
     5 #define LL long long
     6 #define N 10000001
     7 #define MAX 100000
     8 #define MIN 1
     9 #define mem(a, b) memset(a, b, sizeof(a))
    10 using namespace std;
    11 
    12 int flag, pre[N], n, a, b, num[N], Max=1;
    13 
    14 int fi(int x){
    15     return pre[x]==x?x:pre[x]=fi(pre[x]);
    16 }
    17 
    18 void uni(int x, int y){
    19     int fx=fi(x), fy=fi(y);
    20     if(fx!=fy){
    21         pre[fx]=fy;
    22         num[fy]+=num[fx]; 
    23     }
    24 }
    25 
    26 int main(){
    27     while(scanf("%d",&n)!=EOF){
    28         for(int i=1; i<=10000000; i++){
    29             pre[i]=i;
    30             num[i]=1;
    31         }
    32         for(int i=0; i<n; i++){
    33             scanf("%d%d",&a, &b);
    34             Max=max(Max, max(a, b));
    35             uni(a, b);
    36         }
    37         int sum=0;
    38         for(int i=1; i<=Max; i++){
    39             sum=max(sum, num[i]);
    40         }
    41         printf("%d
    ",sum);
    42     }
    43 } 
  • 相关阅读:
    node.js基础回顾
    PHP基础回顾之表单(二)
    PHP基础回顾(一)
    知识图谱Knowledge Graph
    Qt addStretch()详解
    Qt实现 QQ好友列表QToolBox
    Qt5
    用户级线程和内核级线程
    TCP状态转换图、滑动窗口、半连接状态、2MSL
    理解tcp顺序释放操作和tcp的半关闭
  • 原文地址:https://www.cnblogs.com/cake-lover-77/p/10918471.html
Copyright © 2011-2022 走看看