D2. 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 a consisting of n integers. In one move you can choose any ai and divide it by 2 rounding down (in other words, in one move you can set ai:=⌊ai2⌋).
You can perform such an operation any (possibly, zero) number of times with any ai.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don’t forget that it is possible to have ai=0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1≤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 n integers a1,a2,…,an (1≤ai≤2⋅105), where ai is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k 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
Solution
给出一组数,可以任意一个数 a i a_i ai变成 a i 2 \frac {a_i} {2} 2ai,该操作可以执行无数次,求问得到k个数相等时最少需要的操作次数。把所有的数进行减半操作直到0为止,然后把每次减半的操作次数记录在对应的数组内,然后对所有数组的操作次数进行排序,把所有可能得到的数值遍历一遍,取对应数组内的前k个数之和最小即为答案。
Code
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 2e5+5;
const int inf = 0x3f3f3f3f;
typedef long long ll;
int n,k,temp;
vector<int> v[maxn];
int main() {
cin >> n >> k;
for(int i=0;i<n;i++) {
cin >> temp;
int cnt = 0;
while(temp) {
v[temp].push_back(cnt);
cnt++;
temp /= 2;
}
v[0].push_back(cnt);
}
for(int i=0;i<maxn;i++) {
sort(v[i].begin(),v[i].end());
}
ll ans = inf;
for(int i=0;i<maxn;i++) {
if(v[i].size() >= k) {
ll res = 0;
for(int j=0;j<k;j++) {
res += v[i][j];
}
ans = min(ans,res);
}
}
cout << ans << endl;
}