CodeForces - 1213D2-Equalizing by Division (hard version)(简单思维)

CodeForces - 1213D2-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.

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个数ai,可以对ai进行操作,即ai = ⌊ai/2⌋,问到得到K个相同的数最少需要操作多少次。

题目分析:

题目比较简单,因为数据范围比较小,直接记录数量,枚举一下就可。

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <map>
#include <stack>
#include <vector>
#include <queue>
#define maxn 200005
#define INF 0x3f3f3f3f
using namespace std;

typedef long long ll;

int n, k;
int a[maxn], vis[maxn], num[maxn];

int main()
{
    while(cin >> n >> k)
    {

        memset(a, 0, sizeof(a));
        int flag = 0;
        for(int i = 1; i <= n; i ++)
        {
            cin >> a[i];
            vis[a[i]] ++;
            if(vis[a[i]] == k)
                flag = 1;
        }
        if(flag == 1)
        {
            cout << 0 << endl;
            continue;
        }
        else
        {
            memset(vis, 0, sizeof(vis));
            memset(num, 0, sizeof(num));
            sort(a + 1, a + n + 1);
            int ans = INF;
            for(int i = 1; i <= n; i ++)
            {
                int cnt = 0;
                while(a[i])
                {
                    vis[a[i]] ++;
                    num[a[i]] += cnt;
                    if(vis[a[i]] == k)
                        ans = min(ans, num[a[i]]);
                    cnt ++;
                    a[i] /= 2;
                }   
            }
            cout << ans << endl;          
        }
        

    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值