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: Prime Gaming (Hard Version)

Begin with one fixed array of pile values and forget summing over all arrays for now.
Who survives depends on deletions, so first solve the game structure.
For a fixed configuration, avoid direct value comparisons by introducing a threshold $a$.
Ask only: can Alice force the final value $x \ge a$?

Answer to Hint 2: binarize values:

  • bit $0$: pile value $< a$
  • bit $1$: pile value $\ge a$

Now Alice wants final bit $1$, Bob wants final bit $0$.

Define a minimax DP on states of the current sequence:

  • current length $l$
  • current binary mask of those $l$ piles

Transition = remove one currently good index $i$ (after reindexing), i.e. delete bit $i$ from the mask.

The good-index pattern is fixed by position in the current sequence (index $i$ is legal iff original good[i] is true in that length).
So for each $l$, legal removals are known and independent of mask values.

That lets you compute all masks of length $l$ from masks of length $l - 1$.

Base case: $l = 1$.
If only one bit remains, the game ends and result equals that bit.

For larger $l$, apply alternating minimax:

  • Alice turn: OR over legal moves
  • Bob turn: AND over legal moves

After this DP, each length-$n$ binary mask is classified as winning or losing for Alice (for the threshold query $x \ge a$).

Group winning masks by count $c$ of zeros (or ones, either convention works).
Let that count be $K_c$.

For a fixed threshold $a$, if a mask has exactly $c$ zeros:

  • each zero-position has $(a - 1)$ choices in $[1, a-1]$
  • each one-position has $(m - a + 1)$ choices in $[a, m]$

So this mask corresponds to

$$ (a - 1)^c (m - a + 1)^{n-c} $$

arrays.

Therefore

$$ F(a) = \#\{\text{arrays with final } x \ge a\} = \sum_{c=0}^{n} K_c (a - 1)^c (m - a + 1)^{n-c}. $$

And the requested sum is

$$ \sum_{\text{arrays}} x = \sum_{a=1}^{m} F(a). $$

Complexity idea:

  • DP over all masks across all lengths: $O(n 2^n)$ states, each with up to $n$ transitions, acceptable due to $\sum 2^n \le 2^{20}$
  • Then evaluate $F(a)$ for all $a \in [1,m]$ with $n+1$ coefficients $K_c$

This fits because $\sum m \le 10^6$.

Implementation detail from many accepted solutions: keep masks with an extra leading sentinel bit to encode current length cleanly in one array, and precompute popcount for masks up to $2^{20}$ once.