zoukankan      html  css  js  c++  java
  • Equalizing by Division

    The only difference between easy and hard versions is the number of elements in the array.

    You are given an array aa consisting of nn integers. In one move you can choose any aiai and divide it by 22 rounding down (in other words, in one move you can set ai:=ai2ai:=⌊ai2⌋).

    You can perform such an operation any (possibly, zero) number of times with any aiai.

    Your task is to calculate the minimum possible number of operations required to obtain at least kk equal numbers in the array.

    Don't forget that it is possible to have ai=0ai=0 after some operations, thus the answer always exists.

    Input

    The first line of the input contains two integers nn and kk (1kn21051≤k≤n≤2⋅105) — the number of elements in the array and the number of equal numbers required.

    The second line of the input contains nn integers a1,a2,,ana1,a2,…,an (1ai21051≤ai≤2⋅105), where aiai is the ii-th element of aa.

    Output

    Print one integer — the minimum possible number of operations required to obtain at least kk equal numbers in the array.

    Examples

    Input
    5 3
    1 2 2 4 5
    
    Output
    1
    
    Input
    5 3
    1 2 3 4 5
    
    Output
    2
    
    Input
    5 3
    1 2 3 3 3
    
    Output
    0
    题目大意:数组中有n个元素,每次操作可以使一个元素变为其1/2,问最少执行多少步,才能使数组中有k个相等的元素
    题解:首先我们要排一下序,从小到大排,然后对每个,枚举每个元素,枚举的同时除二,同时用一个数组cnt记录在除二的过程的出现的数字,并记录一下,在用一个数组num记录arr[i]变成当前状态需要几步。
    #include<bits/stdc++.h>
    using namespace std;
    const int N=2E5+7;
    const int INF=1e9+7;
    int arr[N];
    int num[N];
    int cnt[N];
    int main(){
        int n,m;
        cin>>n>>m;
        for(int i=1;i<=n;i++)    scanf("%d",&arr[i]);
        sort(arr+1,arr+1+n);
        int ans=INF;
        for(int i=1;i<=n;i++){
            int x=arr[i];
            int temp=0;
            while(x){
                cnt[x]++;
                num[x]+=temp;
                if(cnt[x]==m) {
                    ans=min(ans,num[x]);
                }
                temp++;
                x/=2;
            }
        }
        cout<<ans<<endl;
        
        return 0;
    }


  • 相关阅读:
    TCP/IP(四)网络层
    TCP/IP(二)物理层详解
    TCP/IP(一)之开启计算机网络之路
    TCP/IP中你不得不知的十大秘密
    ASP .NET Core 基本知识点示例 目录
    微服务 + Docker + Kubernetes 入门实践 目录
    ASP.NET Core 中的实时框架 SingalR
    ASP.NET Core WebAPI中使用JWT Bearer认证和授权
    .NET Core 中的通用主机和后台服务
    EF Core 实现多租户
  • 原文地址:https://www.cnblogs.com/Accepting/p/11594978.html
Copyright © 2011-2022 走看看