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

扫描二维码关注公众号,回复: 8846597 查看本文章

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;
}
发布了27 篇原创文章 · 获赞 11 · 访问量 3586

猜你喜欢

转载自blog.csdn.net/Megurine_Luka_/article/details/102083829