D2. Equalizing by Division (hard version)

D2. Equalizing by Division (hard version)

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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
Copy
5 3
1 2 2 4 5
output
Copy
1
input
Copy
5 3
1 2 3 4 5
output
Copy
2
input
Copy
5 3
1 2 3 3 3
output
Copy
0

题意:给了n个数 每次操作可以任意选一个数对他除以2向下取整代替这个数,问让这n个数中,至少有k个数一样 至少要多少次操作

题解:暴力记录所有数除以2得到另一个数需要的操作次数,用二维数组 v[ i ][ j ] 表示a[ j ] 变成 i 需要的操作次数,而v[ i ].size( )的大小就表示可以变成 i 的数有几个,如果v[i].size()>=k,对v[i]进行排序,取操作次数最少的前k个,累加求和取最小即可

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int>v[200005];
int a[200005];
int main()
{
    int n,k,ans=200000005;
    cin>>n>>k;
    for(int i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n);
    for(int i=0;i<n;i++)
    {
        int x=a[i],t=0;
        while(x)
        {
            v[x].push_back(t);//a[i]变成x需要操作t次
            x=x/2;
            t++;  
        }
    }
    for(int i=0;i<200005;i++)
    {
        if(v[i].size()>=k)//如果可以变成i的个数>=k
        {
            int sum=0;
            sort(v[i].begin(),v[i].end());//排序,取操作数最小的k个数
            for(int j=0;j<k;j++)
                sum=sum+v[i][j];
            ans=min(ans,sum);
        }
    }
    cout<<ans<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/-citywall123/p/11644544.html