D2. Equalizing by Division (hard version)

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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

You are given an array 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 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 a.

Output

Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.

Examples
input
Copy
5 3
1 2 2 4 5
output
Copy
1
input
Copy
5 3
1 2 3 4 5
output
Copy
2
input
Copy
5 3
1 2 3 3 3
output
Copy
0

 

题意:给了n个数 每次操作可以任意选一个数对他除以2向下取整代替这个数,问让这n个数中,至少有k个数一样 至少要多少次操作

题解:暴力记录所有数除以2得到另一个数需要的操作次数,用二维数组 v[ i ][ j ] 表示a[ j ] 变成 i 需要的操作次数,而v[ i ].size( )的大小就表示可以变成 i 的数有几个,如果v[i].size()>=k,对v[i]进行排序,取操作次数最少的前k个,累加求和取最小即可

 

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int>v[200005];
int a[200005];
int main()
{
    int n,k,ans=200000005;
    cin>>n>>k;
    for(int i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n);
    for(int i=0;i<n;i++)
    {
        int x=a[i],t=0;
        while(x)
        {
            v[x].push_back(t);//a[i]变成x需要操作t次
            x=x/2;
            t++;  
        }
    }
    for(int i=0;i<200005;i++)
    {
        if(v[i].size()>=k)//如果可以变成i的个数>=k
        {
            int sum=0;
            sort(v[i].begin(),v[i].end());//排序,取操作数最小的k个数
            for(int j=0;j<k;j++)
                sum=sum+v[i][j];
            ans=min(ans,sum);
        }
    }
    cout<<ans<<endl;
    return 0;
}

 

相关文章:

  • 2021-09-03
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2019-10-27
  • 2021-08-05
  • 2021-07-15
猜你喜欢
  • 2021-11-21
  • 2022-12-23
  • 2022-01-11
  • 2022-01-26
  • 2021-07-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案