Codeforces 437B The Child and Set (贡献+贪心)

链接:https://codeforces.com/contest/437/problem/B

题意:给出n,sum,构造一个序列满足:整数,无重复,范围1-n,sigma(ai)=sum,输出长度和各个元素。n<1e5

题解:考虑1-n的每个整数对sum的贡献,在从大往下取(贪心)。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define lowbit(x) ((x)&-(x))

const int maxn=1e5+5;
int sum, n;
vector<int> ans, lbt[maxn];

int main()
{
    ios::sync_with_stdio(false); cin.tie(0);
    cin>>sum>>n;
    int tmax=-1;
    for(int i=1; i<=n; i++)
    {
        lbt[lowbit(i)].push_back(i);
        tmax=max(tmax, lowbit(i));
    }
    for(int i=tmax; i>=1; i--)
    {
        for(auto v:lbt[i]){
            if(sum>=i){
                sum-=i; ans.push_back(v);
            }
            else break;
        }
        if(sum==0) break;
    }
    if(sum){cout<<"-1"; return 0;}
    cout<<ans.size()<<"\n";
    for(auto v:ans)
        cout<<v<<" ";
    return 0;
}

 

posted @ 2019-10-30 23:22  N_Yokel  阅读(155)  评论(0编辑  收藏  举报