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
inputCopy
5 3
1 2 2 4 5
outputCopy
1
inputCopy
5 3
1 2 3 4 5
outputCopy
2
inputCopy
5 3
1 2 3 3 3
outputCopy
0

#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <numeric>
#include <math.h>
typedef long long ll;
using namespace std;
const int N = 2e5+11;

int n,k;
vector<int>a[N];

int main(){
	scanf("%d%d",&n,&k);
	for(int i = 1;i <= n;i++){
		int x,k = 0;
		scanf("%d",&x);
		while(x){
			a[x].push_back(k);
			x /= 2;
			k++;
		}
	}
	int ans = 1e9;
	for(int i = 1;i <= 200*1000;i++){
		if(a[i].size() >= k){
			sort(a[i].begin(),a[i].end());
			ans = min(ans,accumulate(a[i].begin(),a[i].begin()+k,0));
		}
	}
	printf("%d\n",ans);
	return 0;
}
上一篇:python – Algo用于将数字划分为(几乎)相等的整数


下一篇:D1. Equalizing by Division (easy version)