D2. Equalizing by Division (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe 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.InputThe 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
.OutputPrint one integer — the minimum possible number of operations required to obtain at least kk
equal numbers in the array.
题意:
n个数,每个数可以除2向下取整,问你保证最小有k个数相同操作的最小步数;
解题:
其实就是暴力,用一个二维数组ve[ i ][ j ];表示变成i可能有的步数;
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=2e5+5;
int a[N];
vector<int> ve[N];
int main(){
int n,k;
cin>>n>>k;
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0;i<n;i++){
int cnt=0;
int t=a[i];
ve[t].push_back(0);
while(t){
cnt++;
t>>=1;
ve[t].push_back(cnt);
}
}
int ans=n*n+5;
for(int i=0;i<N;i++){
if(ve[i].size()<k) continue;
sort(ve[i].begin(),ve[i].end());
int cnt=0;
for(int j=0;j<k;j++) cnt+=ve[i][j];
ans=min(ans,cnt);
}
cout<<ans<<endl;
return 0;
}