Official

D - Delete Different Editorial by evima


We call a state where the sequence contains only one distinct value a steady state. We also allow performing the operation in a steady state.

It suffices to find, for each \(k=0,1,\cdots,N-1\), the number of sequences of length \(N\) that are in a steady state after \(k\) operations. (A sequence in a steady state after \(k\) operations is counted even if it reached a steady state during an earlier operation.)

Here, consider the reverse operation.

Consider undoing one step for a sequence \(a=(a_1,a_2,\cdots,a_s)\). For each \(i\), zero or more terms can be inserted between \(a_i\) and \(a_{i+1}\), and the number of possible inserted sequences is determined by the number of inserted elements and whether \(a_i=a_{i+1}\). Also, zero or more terms can be appended after \(a_s\).

Based on this observation, we can consider the following DP.

  • \(X[k][len]\): the number of sequences of length \(len\) obtained by performing the reverse operation \(k\) times starting from \((1,1)\), where the reverse operation does not append values at the end. Here, it is not essential that the initial value is \(1\); what matters is only that the first and last elements are the same.
  • \(Y[k][len]\): the number of sequences of length \(len\) obtained by performing the reverse operation \(k\) times starting from \((1,2)\), where the reverse operation does not append values at the end. Here, it is not essential that the initial values are \(1,2\); what matters is only that the first and last elements are different.
  • \(Z[k][len]\): the number of sequences of length \(len\) obtained by performing the reverse operation \(k\) times starting from \((1)\). Here, the reverse operation does include appending values at the end.

\(X,Y,Z\) can be computed by setting up recurrences according to their definitions.

The number of sequences obtained by performing the reverse operation \(k\) times starting from \((1,1,\cdots,1)\) can be computed from \(X\) and \(Z\).

Implementing the above computation straightforwardly yields an \(O(N^3)\)-time algorithm.

Sample Solution (C++)