---
id: 1756
lang: en
translation_of: index.md
source_sha256: 4b008c10065c7df4df1ed89f88c7ab4b1acff841b08b4db937b294ac977894b0
title: "Codeforces 1174D: Ehab and the Expected XOR Problem — Solution"
description: "Take prefix XOR sums, require them to be distinct with no pair XORing to x, then handle x ≥ 2^n and x < 2^n separately."
tags: ["OI","Bitwise Operations","Ad Hoc","Prefix Sums"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## 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.

<!--more-->

## Code

```cpp
// 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;
}
```
