Codeforces 1213D2 【思维】

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

Source

Codeforces 1213D2 Equalizing by Division (hard version)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值