Official

E - Permutation Editorial by en_translator


Consider the following DP (Dynamic Programming).

\(\mathrm{DP}_S\) (\(S\) is a subset of \(\{1, 2, 3, \dots, N\}\)): the number of permutations where the set first \(|S|\) elements is equal to \(S\) and that satisfies all the given conditions such that \(X_i \le |S|\)

Let us consider the transition from an arbitrary \(\mathrm{DP}_S\) to \(\mathrm{DP}_{S \cup \{x\}}\), where the \(|S|+1\)-th element of \(a\) is determined to \(x\). Here, the transition is valid if:

  • \(x \notin S\), and
  • For all \(i\) such that \(X_i = |S \cup \{x\}|\), \(S \cup \{x\}\) contains at most \(Z_i\) numbers less than or equal to \(Y_i\).

The answer for the problem is \(\mathrm{DP}_{\{1, 2, 3, \dots, N\}}\).
Since there are \(2^N\) states, and each transition takes an \(O(N)\) time, it can be solved in a total of \(O(2^N N)\) time.

For implementation, we can regard \(S\) as an integer \(\displaystyle \sum_{i \in S} 2^{(i - 1)}\) so that it can be used as an index of an array. Most languages is equipped with a bit operator which enables to obtain an integer corresponding to \(S \cup \{x\}\) from an integer corresponding to \(S\), which simplifies the implementation.
Such a technique of implementation is so general that the DP where the set is used as an index is called bitmask DP.

posted:
last update: