Equalizing by Division 思维

传送门

The only difference between easy and hard versions is the number of elements in the array.

You are given an array aa consisting of nn integers. In one move you can choose any aiai and divide it by 22 rounding down (in other words, in one move you can set ai:=⌊ai2⌋ai:=⌊ai2⌋).

You can perform such an operation any (possibly, zero) number of times with any aiai.

Your task is to calculate the minimum possible number of operations required to obtain at least kk equal numbers in the array.

Don't forget that it is possible to have ai=0ai=0 after some operations, thus the answer always exists.

Input

The first line of the input contains two integers nn and kk (1≤k≤n≤2⋅1051≤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 nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤2⋅1051≤ai≤2⋅105), where aiai is the ii-th element of aa.

Output

Print one integer — the minimum possible number of operations required to obtain at least kk 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

题解:

题意概括:给你一列n个数字,你能做的操作是对任意一个数对2向下取整,要想数列中有k个相同的数,求你的最小操作数。

对每个数字循环向下取整,用cnt[x]记录每次向下取整得到x的总数,用num[x]记录变成x所需最小步数。当然需要对原数列从小到大排序一下,因为如果从较小的x开始寻找的话,自然是从较小的数向下取整时步数较小。

//#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn=2e5+10;
const int inf=0x3f3f3f3f;

int a[maxn];
int cnt[maxn],num[maxn];//cnt函数用来记录除以2之后产生的数,num用来记录到达m个相同数时,需要进行的步数 

int main()
{
//	freopen("input.txt","r",stdin);
	
	int n,k;
	cin>>n>>k;
	for(int i=0;i<n;i++) cin>>a[i];
	int ans=inf;
	sort(a,a+n);
	for(int i=0;i<n;i++)
	{
		int temp=0;//temp记录while循环中此前是第几步 
		int x=a[i];
		while(x)
		{
			cnt[x]++;
			num[x]+=temp;
			if(cnt[x]==k) ans=min(ans,num[x]);//整个循环结束,取把变成每个相同的数字需要的最少步数 			
			x/=2;
			temp++;
		}
	}
	cout<<ans;
	
	return 0;
 } 

时间复杂度:

2的18次方是1e5.因此for循环中的while循环复杂度是18.

time=2e5*18=3e6+,,给了2秒完全足够。

空间复杂度:

space=2e5,,也够了。

新知:

1、向上取整:比自己大的最小整数。如(5/2)的向上取整的结果是3。

     向下取整:比自己小的最大整数。如(5/2)的向下取整的结果是2。

     向上取整和向下取整仅与定义有关,与四舍五入无关。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值