CF1988C 题解

· · 题解

思路

其实这题 a_i=n\operatorname{xor}\text{(n 的从高到低第 i 个 1 的权值)},最后补一个 n 就行。另外若 n=2^m 是例外,只能直接输出 n。

代码

方法 1

# include <bits/stdc++.h>
# define I return
# define AK 0
# define IOI ;
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int t, m;
ll n, a[500005];
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> t;
    while (t --) {
        cin >> n;
        if (n == (n & -n)) {
            cout << "1\n" << n << '\n';
            continue ;
        }
        m = 0;
        for (int i = 62; ~i; -- i)
            if (n >> i & 1)
                a[++ m] = n ^ (1ll << i);
        a[++ m] = n;
        cout << m << '\n';
        for (int i = 1; i <= m; ++ i)
            cout << a[i] << ' ';
        cout << '\n';
    }
    I AK IOI
}

方法 2

# include <bits/stdc++.h>
# define I return
# define AK 0
# define IOI ;
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int t, m;
ll n, a[500005], tmp;
ll f (ll x) { //highbit
    while (x != (x & -x))
        x ^= x & -x;
    return x;
}
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> t;
    while (t --) {
        cin >> n;
        if (n == (n & -n)) {
            cout << "1\n" << n << '\n';
            continue ;
        }
        m = 0, tmp = n;
        while (n)
            a[++ m] = tmp ^ f (n), n ^= f (n);
        a[++ m] = tmp;
        cout << m << '\n';
        for (int i = 1; i <= m; ++ i)
            cout << a[i] << ' ';
        cout << '\n';
    }
    I AK IOI
}