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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值