Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Hints: XOR-factorization

You must output $k$ numbers in $[0, n]$. If you ignored the XOR condition for a moment, what is the largest possible value of $a_1 + a_2 + \cdots + a_k$, and when can you achieve it with every $a_i$ as large as allowed?

Answer to Hint 1: Trivially $a_i \le n$, so

$$ \sum_{i=1}^{k} a_i \le kn, $$

with equality exactly when every $a_i$ equals $n$.

Now bring XOR back in: what is

$$ \underbrace{n \oplus n \oplus \cdots \oplus n}_{k\text{ times}} $$

as a function of whether $k$ is odd or even?

Answer to Hint 2: XOR satisfies $x \oplus x = 0$, so identical values cancel in pairs.

  • If $k$ is odd, every pair cancels except one copy of $n$, so the XOR is $n$.
  • If $k$ is even, everything pairs off and the XOR is $0$.

Therefore, when $k$ is odd, taking $a_1 = \cdots = a_k = n$ satisfies both the XOR constraint and the upper bound $kn$. That case is finished.

For even $k$, all-$n$ is impossible: it makes the XOR equal to $0$, but you need the XOR to be $n$.

Try using as many copies of $n$ as you can, and reserve one slot to fix the XOR. Suppose

$$ a_1 = a_2 = \cdots = a_{k-1} = n $$

and you are free to choose only $a_k$. What XOR equation does $a_k$ need to satisfy? What choice of $a_k \in [0,n]$ maximizes the sum while satisfying that equation?

Answer to Hint 4: You need

$$ \underbrace{n \oplus \cdots \oplus n}_{k-1\text{ times}} \oplus a_k = n. $$

Because $k-1$ is odd, the XOR of the first $k-1$ copies equals $n$, so the equation becomes $n \oplus a_k = n$, hence $a_k = 0$.

That construction uses $k-1$ copies of $n$ and one $0$, so the sum is $(k-1)n$. Every other $a_i$ is already at the maximum possible value $n$.

To sanity-check with the samples:

  • First line of the statement: $n = 5$, $k = 4$. Even $k$, so compare your target sum $(k-1)n$ with the note’s sum $15$.
  • Second line: $n = 4$, $k = 3$. Odd $k$, so compare $kn$ with the note’s sum $12$.

If these match your formulas, you have the right objective value; any answer that hits that sum and respects $0 \le a_i \le n$ with the correct XOR is acceptable.

Answer to Hint 6: Both match: $(4-1)\cdot 5 = 15$ and $3\cdot 4 = 12$.

Implementation-wise you can output the explicit patterns above:

  • Odd $k$: print $k$ copies of $n$.
  • Even $k$: print $k-1$ copies of $n$ and a single $0$.

The reference model_sol.cpp uses an equivalent bitwise construction (still starting from all $n$ when $k$ is even) instead of printing one large zero explicitly; either description is fine as long as you prove to yourself that the XOR ends at $n$ and the sum stays at $(k-1)n$.