02

· · 题解

落实同学题单.ing

思路

首先将 n + 1,这样就可以以考虑空集了。

先考虑 n = 2^k,显然构造 2^0\sim 2^{k-1} 即可(注意考虑了空集)。

接下来考虑怎么再补出一个 2^x,举个例子,设 n = (0100100101)_2

1111100000
1111011000
1111011011

如果我们要补出一个 2^x,就将第 x+1 \sim k-1 位取反,第 1 \sim x-1 设为 0 即可,考虑为什么,因为若第 y 位与其异或满足 y > x 时,会被前面的情况包含不产生贡献,而 < x 的每个位置都可以产生贡献,所以贡献了 2^x 个数。

代码

#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, a[N], cnt;
vector<int> ans;
int main() {
    int T;
    cin >> T;
    while (T --) {
        ans.clear(), cnt = 0;
        cin >> n;
        n ++;
        int t = n;
        while (t) {
            a[++ cnt] = t % 2;
            t /= 2;
        }
        reverse(a + 1, a + cnt + 1);
        for (int i = 0; i < cnt - 1; i ++)
            ans.push_back(1 << i);
        n = (1 << cnt - 1);
        for (int i = 2; i <= cnt; i ++) {
            if (a[i])
                ans.push_back(n + (1 << cnt - i));
            n += (1 << cnt - i) * !a[i];
        }
        cout << ans.size() << '\n';
        for (int i : ans)
            cout << i << ' ';
        cout << '\n';
    }
    return 0;
}