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

Posted yokel062

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()<<"
";
    for(auto v:ans)
        cout<<v<<" ";
    return 0;
}

 

以上是关于Codeforces 437B The Child and Set (贡献+贪心)的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces 437B & 437C

Codeforces 438D The Child and Sequence

codeforces438D The Child and Sequence

CodeForces 438D The Child and Sequence

Codeforces437 B. The Child and Set

Codeforces 437D The Child and Zoo