跳到正文

题解

题解:P9256 [PA 2022] Muzyka pop 2

wayneoi约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月7日
篇幅
约 2 分钟
获赞
1
题目
P9256

版本

  1. v1当前

题目传送门

答案要满足序列的字典序最小, 序列中所有数的二进制表示中 1 的个数之和恰好为 n。

从前往后比较,优先选择较小的数, 如果一个串是另一个串的前缀,则非前缀串的字典序更大,每次尽可能选择最小的 x,使得 1 的个数之和不超过 n。

从 x = 1 开始,逐步增加 x,累加其二进制中 1 的个数(使用 __builtin_popcount 函数),直到总和 s ≥ n。

从最大的 x 开始反向检查,如果移除某个数后仍能满足 s ≥ n,则移除它。

  • 时间复杂度:O(n)

代码

C++
#include <bits/stdc++.h>
using namespace std;
vector<int> ans;
int n, sum, x;
int main(){
    cin >> n;
    // 贪心选择最小的x,直到sum >= n。
    while(sum < n) x++, sum += __builtin_popcount(x);
    // 反向检查是否可以移除某些数。
    for(int i = x; i >= 1; i--){
        if(sum - __builtin_popcount(i) >= n) sum -= __builtin_popcount(i);
        else ans.push_back(i);
    }
    // 输出结果。
    cout << ans.size() << "\n";
    for(int num : ans) cout << num << " ";
    return 0;
}

求过🙏🏻🙏🏻🙏🏻!

原文