Equalizing by Division (hard version)

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:=⌊ai2⌋ai:=⌊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 (1≤k≤n≤2⋅1051≤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 (1≤ai≤2⋅1051≤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.

 

做法:先进行排序来达到数组记录的一定是最小的目的,每个数不断除2向下取整,vis用来记录是否该数能出现k次,num来记录该数出现k次需要多少次操作,ans数组即是答案,最后遍历ans数组取出最小值即得到答案。

#include 

using namespace std;

int a[200010];
int vis[200010];
int num[200010];
int ans[200010];

int main()
{
    int n,k;
    int flag=0;
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        vis[a[i]]++;
        if(vis[a[i]]==k)
            flag=1;
    }
    if(flag)
    {
        printf("0");
        return 0;
    }
    memset(vis,0,sizeof(vis));
    memset(num,0,sizeof(num));
    memset(ans,0x3f3f3f3f,sizeof(ans));
    sort(a+1,a+1+n);
    int m;
    int cont;
    for(int i=1;i<=n;i++)
    {
        m=a[i];
        cont=0;
        while(m)
        {
            vis[m]++;
            num[m]+=cont;
            cont++;
            if(vis[m]==k)
            {
                ans[m]=num[m];
            }
            m/=2;
        }
    }
    int minn=0x3f3f3f3f;
    for(int i=1;i<=200000;i++)
    {
        minn=min(minn,ans[i]);
    }
    printf("%d",minn);
    return 0;
}

 

你可能感兴趣的:(Equalizing by Division (hard version))