Codeforces Round #582 (Div. 3) D2. Equalizing by Division (hard version)(思維+枚舉暴力)

題目鏈接

https://codeforces.com/contest/1213/problem/D2

題目描述

You are given an array a consisting of n integers. In one move you can choose any aiai 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


思路

我是受過專業訓練的,1600分左右的題一般都會做,除非想不到。

設一個vector類型的二維數組v[],其中數組v[i]存儲a[]中各個數字除幾次能得到i,拿樣例1來說,v[2]={0,0,1,1},2和2除零次得到數字2,而4和5除一次得到數字2。

我們可以通過nlog(max(a[i]))的算法完成對v[]的統計,具體詳見代碼。

接下來,只需判斷v[i]的size是否大於k,並且取前k小的數即可。

代碼

#include <bits/stdc++.h>
#define ll long long
#define maxn 200010
using namespace std;
int n,k,a[maxn];
vector<int>v[maxn];

int main(){
	int i,j;
	scanf("%d%d",&n,&k);
	for(i=1;i<=n;i++)scanf("%d",&a[i]);
	for(i=1;i<=n;i++){
		v[a[i]].push_back(0);
		int cnt=0;
		while(a[i]){
			a[i]/=2;
			cnt++;
			v[a[i]].push_back(cnt);
		}
	}
	int ans=n*100;
	for(i=0;i<maxn;i++){
		if(v[i].size()>=k){
			int q=0;
			sort(v[i].begin(),v[i].end());
			for(j=0;j<k;j++)q+=v[i][j];
			ans=min(ans,q);
		}
	}
	cout<<ans;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章