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


你可能感兴趣的:(CF练习记录,个人联系记录)