链接:https://codeforces.com/contest/1213/problem/D2
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.
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
代码:
#include <bits/stdc++.h>
using namespace std;
long long n,k,s=0,a[200005],b[200005]={0},c[200005]={0},m=100000007;
int main()
{
cin>>n>>k;
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
{
int x=0;
while(a[i])
{
if(c[a[i]]<k)
{
c[a[i]]++;
b[a[i]]+=x;
}
if(c[a[i]]==k)
{
if(b[a[i]]<m)
m=b[a[i]];
}
a[i]/=2;
x++;
}
}
cout<<m;
return 0;
}