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.

    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)

    思路:

    简单并查集

    代码:

    int n;
    struct node{
        int x,y;
    }
    Pair[100005];
    
    int cn;
    int a[200005];
    int ct[200005];
    int fa[200005];
    
    int findFa(int x){
        return fa[x]==x?fa[x]:fa[x]=findFa(fa[x]);
    }
    
    void Union(int x,int y){
        int fx=findFa(x);
        int fy=findFa(y);
        if(fx!=fy){
            fa[fx]=fy;
        }
    }
    
    
    
    int main(){
        map<int,int> mp;
    
        while(scanf("%d",&n)!=EOF){
            mp.clear();
            cn=0;
            rep(i,1,n){
                scanf("%d%d",&Pair[i].x,&Pair[i].y);
                if(mp[Pair[i].x]==0){
                    mp[Pair[i].x]=1;
                    a[++cn]=Pair[i].x;
                }
                if(mp[Pair[i].y]==0){
                    mp[Pair[i].y]=1;
                    a[++cn]=Pair[i].y;
                }
            }
            sort(a+1,a+1+cn);
            rep(i,1,cn) fa[i]=i;
            rep(i,1,n){
                int px=lower_bound(a+1,a+1+cn,Pair[i].x)-a;
                int py=lower_bound(a+1,a+1+cn,Pair[i].y)-a;
                Union(px,py);
            }
            mem(ct,0);
            int ans=1;
            rep(i,1,cn){
                int t=findFa(i);
                ct[t]++;
                ans=max( ans,ct[t] );
            }
            printf("%d
    ",ans);
        }
    
        return 0;
    }
  • 相关阅读:
    判断无向图G是否连通
    图的深度优先搜索与广度优先搜索
    整数变换问题
    按层次遍历二叉树
    交叉链表
    二元查找树转换成一个排序的双向链表
    简单计算器的实现
    二叉树宽度的计算
    BMP文件的读取与显示
    约瑟夫环问题
  • 原文地址:https://www.cnblogs.com/fish7/p/4334477.html
Copyright © 2011-2022 走看看