B - Between B and B Editorial by evima
- For each \(B = 1, 2, \dots, M\), the value \(X_B\) exists between any two different occurrences of \(B\) in \(A\) (including both ends).
This condition will be referred to simply as “the condition.”
Let’s consider determining the elements of \(A\) from the beginning. When deciding \(A_i\), we choose \(A_i\) such that \((A_1, A_2, \dots, A_i)\) satisfies the condition.
Therefore, let’s consider the following dynamic programming approach.
- Let \(\mathrm{dp}[c][S]\) be the number of ways to determine the first \(c(=0,1,\dots,N)\) elements of \(A\) such that the set of possible values for \(A_{c+1}\) is \(S (\subset \{1,2,\dots,M\})\).
First, any of \(1,2,\dots,M\) can be chosen as \(A_1\). Therefore, \(\mathrm{dp}[0][\{1,2,\dots,M\}] = 1\).
Next, let’s consider what happens when \(c\) and \(S\) are fixed, and we decide \(A_{c+1}\) to be \(a \in S\).
First, due to the condition that \(X_a\) must exist between any two occurrences of \(a\), we remove \(a\) from \(S\). This can be interpreted as not being allowed to add \(a\) again until \(X_a\) is added. Next, we add all \(b\) such that \(X_b = a\) to \(S\). This can be interpreted as allowing \(b\) to be added since \(X_b\) has been added. Let the new set obtained in this way be written as \(S(a)\). The transition in the dynamic programming can be written as follows:
- \(\mathrm{dp}[c+1][S(a)] \xleftarrow{+} \mathrm{dp}[c][S] \quad (a \in S)\)
This is a bitDP. The time complexity is \(\mathrm{O}(NM2^M)\), which is sufficiently fast under the given constraints.
posted:
last update: