Codeforces Equalizing by Division (hard version)

在這裏插入圖片描述
題目大意:
給你一個數組,給定k,定義一個操作爲arr[i]/2,問你至少操作多少次,使數組中存在k個相等的數

解題思路:
首先我們要排一下序,從小到大排,然後對每個,枚舉每個元素,枚舉的同時除二,同時用一個數組cnt記錄在除二的過程的出現的數字,並記錄一下,在用一個數組num記錄arr[i]變成當前狀態需要幾步。

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=2e5+10;
int n,k,ans=0x3f3f3f3f;
int cnt[maxn],nums[maxn],arr[maxn];
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;++i)
        scanf("%d",&arr[i]);
    sort(arr+1,arr+1+n);
    for(int i=1;i<=n;++i)
    {
        int x=arr[i],temp=0;
        while(x)
        {
            cnt[x]++;
            nums[x]+=temp;
            if(cnt[x]==k) ans=min(ans,nums[x]);
            temp++;
            x/=2;
        }
    }
    printf("%d",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章