公式

A - Swapping Game 解説 by evima


For convenience, let \(P_0 \coloneqq (1, 2, \ldots, L)\). Also, the act of obtaining \(C_i\) yen by satisfying \(A = P_i\) after the \(i\)-th operation is simply called achieving \(i\).

For a subsequence \((i_0 \coloneqq 0, i_1, i_2, \ldots, i_n)\) of \((0, 1, 2, \ldots, N)\), a necessary and sufficient condition to achieve all of \(i_1, i_2, \ldots, i_n\) is that

(\(\star\)) \(\mathrm{inv}(P_{i_{j-1}}, P_{i_j}) \leq i_j - i_{j-1}\) holds for all \(j = 1, 2, \ldots, n\).

Here, \(\mathrm{inv}(P, P')\) represents the minimum number of swaps needed to transform \(P\) into \(P'\) by swapping adjacent terms, and is given by the number of inversions of \(P^{-1}P'\).

The problem is to choose a sequence of achievements \((i_0 = 0, i_1, i_2, \ldots, i_n)\) that satisfies the condition (\(\star\)) above and maximize the profit \(C_{i_1} + C_{i_2} + \dots + C_{i_n}\). We solve this problem using dynamic programming. For \(i = 0, 1, \ldots, N\), let

\(\mathrm{dp}[i] = \) (maximum possible profit up to that point when the last achievement was \(i\)).

Then, \(\mathrm{dp}[0] = 0\), and for \(i = 1, 2, \ldots, N\), the following recurrence relation holds:

\[ \mathrm{dp}[i] = \max_{\substack{0 \leq j \lt i,\\ \mathrm{inv}(P_j, P_i) \leq i-j}} \mathrm{dp}[j] + C_i \tag{1}. \]

The answer to the problem is obtained as \(\max_{i = 0}^N \mathrm{dp}[i]\).

Here, note that any permutation \(P\) of \((1, 2, \ldots, L)\) can be transformed into any permutation \(P'\) by at most \(D \coloneqq L(L-1)/2\) swaps of adjacent terms, that is, \(\mathrm{inv}(P, P') \leq D\). This means that in an optimal achievement sequence \((i_0 \coloneqq 0, i_1, i_2, \ldots, i_n)\), \(i_j - i_{j-1} \lt 2D\) holds for all \(j = 1, 2, \ldots, n\) (if this were not the case, we could additionally achieve \({i_{j-1} + D}\) between \(i_{j-1}\) and \(i_j\), contradicting optimality).

Therefore, when computing \(\mathrm{dp}[i]\), we only need to refer to \(O(L^2)\) elements \(\mathrm{dp}[i-2D+1], \ldots, \mathrm{dp}[i-1]\), and the above formula (1) can be replaced with

\[ \mathrm{dp}[i] = \max_{\substack{\max\lbrace 0, i - 2D+1 \rbrace \lt j \lt i,\\ \mathrm{inv}(P_j, P_i) \leq i-j}} \mathrm{dp}[j] + C_i. \]

Using this recurrence relation, we can calculate \(\mathrm{dp}[i]\) for all \(i = 1, 2, \ldots, N\) in \(O(NL^4)\) time overall by computing the number of inversions in \(O(L^2)\) time for each of the \(O(NL^2)\) transitions.

投稿日時:
最終更新: