codeforces 1213D2(贪心+思维)

时间:2022-07-28
本文章向大家介绍codeforces 1213D2(贪心+思维),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意

可以对每个数进行除2的操作,求最少需要操作多少次,使得数组中有k个相同的数

思路

题目中说答案始终存在,因为每个数都可以变成0,但很明显,让数字变成0的情况是不存在的,每个数字不停的除2肯定可以变成1,如果变成0,肯定不是最优解。我们可以使用一个 c n t cnt cnt数组来记录每个数字出现的次数,使用 t o t tot tot数组来记录变成该数需要的次数,因为数据范围最大是 2 ∗ 1 0 5 2*10^5 2∗105,每个数字除2不超过20次就可以变成1,我们遍历一遍数组即可得到答案。

AC代码

#include<bits/stdc++.h>
#define x first
#define y second
#define PB push_back
#define mst(x,a) memset(x,a,sizeof(x))
#define all(a) begin(a),end(a)
#define rep(x,l,u) for(ll x=l;x<u;x++)
#define rrep(x,l,u) for(ll x=l;x>=u;x--)
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long ll;
const int N=2*1e5+10;
const int M=1e6+10;
const int INF=0x3f3f3f3f;
const int MOD=1e9+7;
/*独立思考
不要看测试样例
找性质
试着证明
写完后不盲目交,检查*/
ll a[N],cnt[N],tot[N];
void solve(){
    mst(cnt,0);
    mst(tot,0);
    ll n,k;cin>>n>>k;
    rep(i,0,n) cin>>a[i],cnt[a[i]]++;
    ll ans=1e18;
    sort(a,a+n);
    rep(i,0,n){
    	//有可能数组中a[i]的个数超过了k
        if(cnt[a[i]]>=k) ans=min(ans,tot[a[i]]);
        else{
            int res=1,f=a[i];
            while(f!=1){
                f/=2;
                cnt[f]++;
                tot[f]+=res;
                if(cnt[f]>=k) ans=min(ans,tot[f]);
                res++;
            }
        }
    }
    cout<<ans<<endl;
}
int main(){
    IOS;
    //int t;cin>>t;
    //while(t--){
        solve();
    //}
    return 0;
}