芝士一道构造题,要求序列满足:
- 长度为 的非负整次幂;
- 且和为给定 ;
- 且序列中每个元素的值都为 的非负整次幂。
发现如果不考虑要求一“长度为 的非负整次幂” 的话是很简单的,只需要把 用二进制表示出来就可以了,假设这个序列为 。
如果要满足要求一,就需要把 的一些数拆开,来增加序列的长度。
因为他要求“在此基础上最小化它的字典序“,在长度相同且有序的情况下肯定是 更多的序列字典序更小。
所以把所有大于 的数放到一个小根堆里面,每次把堆顶的数 拆成两个 即可。
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n,t;
int a[114];
signed main () {
cin >> t;
while (t--) {
memset(a,0,sizeof(a));
cin >> n;
a[0] = n;
int x = -1,cnt = 0;
for (int i = 0;i <= 64;i++) {
a[i + 1] = a[i] / 2;
a[i] %= 2;
if (a[i]) {
x = i;
cnt++;
}
}
priority_queue <int,vector <int>,greater <int>> q;
for (int i = 1;i <= x;i++) {
if (a[i]) {
q.push(i);
}
}
while (__builtin_popcount(cnt) != 1) {
if (q.top() == 1) {
a[0] += 2;
q.pop();
} else {
int tp = q.top();
q.pop();
q.push(tp - 1);
q.push(tp - 1);
}
cnt++;
}
while (a[0]--) {
cout << "1 ";
}
while (!q.empty()) {
cout << (1ll << q.top()) << ' ';
q.pop();
}
cout << endl;
}
return 0;
}