CodeForces - 916B(贪心)

题目要求找到一个大小为k的序列s,其二进制权重之和为n,且序列中最大值最小,除去最大值后的序列字典序最大。解决方案是首先构建一个符合权重条件的序列,然后优先拆分最大值以减小序列大小,当最大值不再影响最大值最小条件时,改拆最小值以保持字典序最大。

Jamie and Binary Sequence

题目传送门

题意:给两个数n、k,要你找出一个大小为k的序列s,要求Σ2^si=n,并且该序列最大的数最小,除去最大之后的序列字典序最大。

思路:可以先忽略要求求出一个符合Σ2^si=n的序列,然后拆成符合条件的序列(Si=2*Si-1)。按照题目要求,我们拆最大的数,一直拆到序列大小符合k。这样拆满足了序列最大的数最小,但并没有满足字典序最大。因为当最大的数有多个时,拆到这个数时已经满足序列最大的数最小,这时如果继续拆下去就破坏了字典序最大,所以接下来应该拆最小的数。

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
#include <functional>
#define inf 10000000
using namespace std;
typedef long long ll;
const int MAXN=5e6+10;
const int MAX=1e5+10;
const double eps=1e-6;

priority_queue<int>q,Q;
ll s[MAX];

int main(){
    #ifdef ONLINE_JUDGE
    #else
    freopen("in.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    #endif

    ll n,k;
    cin>>n>>k;
    int cnt=0;
    while (n > 0) {
          ll b=1;
          int a=0;
          while(b*2<=n) b*=2,a++;
          cnt++;
          q.push(a);
          Q.push(a);
          n -= b;
    }
    if(cnt>k){
        cout<<"No"<<endl;
        return 0;
    }
    int temp=cnt;
    while(temp<k){
        int a = Q.top();
        Q.pop();
        a--;
        Q.push(a);
        Q.push(a);
        temp++;
    }
    temp=Q.top();

    while(cnt<k){
       int a = q.top();
       if(temp==a)  break;
       q.pop();
       a--;
       q.push(a);
       q.push(a);
       cnt++;
    }
    temp=0;
    while(q.size()){
        s[temp++]=q.top();
        q.pop();
    }

    while(cnt<k){
        s[cnt-1]=s[cnt-1]-1;
        s[cnt]=s[cnt-1];
        cnt++;
    }

    cout<<"Yes"<<endl;
    for(int i=0;i<cnt;i++){
        if(i==0)
            cout<<s[i];
        else
            cout<<" "<<s[i];
    }
    cout<<endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值