Codeforces Round #582 (Div. 3) D2. Equalizing by Division (hard version)

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⋅10^5) — 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⋅10^5), 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

比赛时一直不知道怎么优化……,看了大佬们的代码发现如此简单……

#include
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=2e5+10;
int a[maxn];
int b[maxn];//当产生的i的个数
int cnt[maxn];//记录变到i所需的最小操作次数
int main(){
	int n,k;
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	sort(a+1,a+n+1);
	for(int i=1;i<=n;i++){
		int j=a[i];
		int noww=0;//记录操作的次数
		while(j!=0){
			if(b[j]>=k){//当产生的i到达次数k时,跳出循环
				break;
			}
			cnt[j]+=noww;
			b[j]++;//每产生一个j,自加
		    j>>=1;
			noww++;
		}
	}
	int minn=inf;
	for(int i=1;i<=maxn;i++){//遍历一遍,找出最小操作次数
		if(b[i]>=k) minn=min(minn,cnt[i]);
	}
	cout<<minn<<endl;
    return 0;
}

你可能感兴趣的:(Codeforces,排序)