zoukankan      html  css  js  c++  java
  • 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)

    输出:

    The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.

    样例输入:
    4
    1 2
    3 4
    5 6
    1 6
    4
    1 2
    3 4
    5 6
    7 8
    样例输出:
    4
    2
    


    #include<iostream>
    #include<stdio.h>
    #include<algorithm>
    #define N 10000001
    //将一个数定义在预处理部分 
    using namespace std;
    int path[N];
    int sum[N]; 
    int findroot(int a){
        int temp=a;
        while (path[a] != -1){
            a=path[a];
        }
        int temp2;
        //改进,使树的高度变矮,宽度增加,方便找根 
        while (path[temp]!= -1){
            temp2=path[temp];
            path[temp]=a;
            temp=temp2;
        }
        return a;
    }
    
    int main (){
        int n;
        while (cin>>n){
            for (int i=1;i<=N;i++){
                path[i]=-1; sum[i]=1;
            }
            int ans=0;
            int a,b;
            while (n--){
                cin >>a>>b;
                a=findroot(a);
                b=findroot(b);
                if (a!=b){
                    path[a]=b;
                    sum[b]+=sum[a];
                    sum[a]=0;
                } 
            }
            for (int i=1;i<=N;i++){
                if (sum[i] > ans)
                ans =sum[i];
            }
            cout<<ans<<endl;
        } 
        return 0;
    }

    跟上一道畅通工程几乎一样

    加了一个在合并集合时同时合并(加)元素个数的功能

    ps:不能想着在找根的过程中数元素个数,因为不一定是叶子,数出来的不对,

  • 相关阅读:
    图文详解——将本地项目上传到码云(gitee)远程仓库
    mysql 查询正在执行的sql
    MySql 缓冲池(buffer pool) 和 写缓存(change buffer) 转
    SQLserver 查询某个表的字段及字段属性
    FastDFS 客户端(二)
    FastDFS 服务器(一)
    C# WPF 正常的项目突然提示 当前上下文中不存在名称“InitializeComponent”
    C# 程序自动重启的解决方法
    Array知识点总结(一)
    JavaScript中为false的情况归档
  • 原文地址:https://www.cnblogs.com/yexiaoqi/p/7232679.html
Copyright © 2011-2022 走看看