zoukankan      html  css  js  c++  java
  • hdu 1856 More is better

    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
    此题是并查集的简单应用。
    #include<stdio.h>
    int father[10000001],rank[10000001];//father[x]记录x的父节点,rank[x]保存根节点数目
    int find(int x)//寻找x的父节点
    {
        if(x!=father[x])
            father[x]=find(father[x]);//回溯时路径压缩
        return father[x];
    }
    void uion(int x,int y)//合并x,y所在的集合
    {
        x=find(x);
        y=find(y);
        if(x==y) return ;
        if(rank[x]>rank[y])
        {
            father[y]=x;
            rank[x]+=rank[y];
        }
        else if(rank[x]<rank[y])
        {
            father[x]=y;
            rank[y]+=rank[x];
        }
        else {
            rank[x]*=2;
            father[y]=x;
        }
    }
    int main()
    {
        int n,i,j,max,a,b;
        while(scanf("%d",&n)!=EOF)
        {
            max=1;
            for(i=0;i<10000000;i++)//初始化
            {
                father[i]=i;
                rank[i]=1;
            }
            for(i=1;i<=n;i++)
            {
                scanf("%d%d",&a,&b);
                uion(a,b);
            }
            max=rank[0];
            for(i=1;i<10000000;i++)//寻找最大的集合
                if(max<rank[i])
                    max=rank[i];
            printf("%d
    ",max);
        }
        return 0;
    }
  • 相关阅读:
    Gym101630A Archery Tournament
    BZOJ2588 Count on a tree
    Redis主从复制
    Redis事务
    Redis持久化RDB和AOF
    设计模式之代理模式
    Spring AOP(面向切面编程)
    基于TCP和UDP的Socket通信
    Ajax无法访问回调函数seccess问题
    SpringBoot Ajax跨域问题(session共享问题)
  • 原文地址:https://www.cnblogs.com/duan-to-success/p/3506057.html
Copyright © 2011-2022 走看看