Olympiad in Informatics

Codeforces 1174D: Ehab and the Expected XOR Problem — Solution

Main Idea

This problem is pretty neat, and I worked it out on my own fairly smoothly.

Consider setting up prefix XOR sums \(\{ S_i \}\). By the property that XOR works bit by bit, clearly every \(S_i\) will be less than \(2^n\). Finally, we can turn the constraints into:

  • No two prefix sums are equal.
  • No pair of prefix sums has an XOR value of \(x\).

Depending on the size of \(x\), we can split this into two cases:

  • \(x \geq 2^n\): no pair \((S_i, S_j)\) has an XOR of \(x\), because the higher bit that exists will not be cancelled out.
  • \(x < 2^n\): we notice that each time we choose a number as a prefix sum, the whole \(2^n\) loses one corresponding number that could be chosen. So each time we choose a number as \(S_i\), we have to mark \(S_i xor \ x\).

Combine the two and that's it.

Code

// CF1174D.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = (1 << 18) + 200;

int n, x, seq[MAX_N];
bool vis[MAX_N];

int main()
{
    scanf("%d%d", &n, &x);
    if (x >= (1 << n))
    {
        int len = (1 << n) - 1;
        printf("%d\n", len);
        for (int i = 1; i <= len; i++)
            printf("%d ", i ^ (i - 1));
    }
    else
    {
        vis[x] = true;
        int tot = 0;
        for (int i = 1, last = 0; i < (1 << n); i++)
            if (vis[i] == false)
                vis[i ^ x] = true, seq[++tot] = i ^ last, last = i;
        printf("%d\n", tot);
        for (int i = 1; i <= tot; i++)
            printf("%d ", seq[i]);
    }
    return 0;
}