Official

E - Range Flip Editorial by en_translator


We will call cards \(l, l + 1, \ldots, r - 1\) simply interval \([l, r)\).

First, we may assume that the operated intervals are disjoint. This is because if we take an optimal solution whose total length of the operated intervals is minimum, the intervals are disjoint. Indeed, if two overlapping intervals \([l_1, r_1)\) and \([l_2, r_2)\) are operated, one can replace \([l_1, r_1), [l_2, r_2)\) with \([\min(l_1, l_2), \max(l_1, l_2)), [\min(r_1, r_2), \max(r_1, r_2))\) without changing the resulting orientations of the cards, but making the total interval length, contradicting the minimality. (The replacement may yield an empty interval, in which case we can simply skip the operation.)

Hence, the problem is boiled down to the following problem:

Split cards \(1,2,\ldots,N\) into \((2K + 1)\) (possibly empty) chunks. For the odd-indexed chunks, the front sides are facing up; for the even-indexed ones, the back sides are. Find the maximum total value of the numbers written on the sides facing up.

Alternatively, we may assume that we are splitting them into non-empty \((2K + 1)\) chunks, but the only first chunk is allowed to be empty.

This can be computed with dynamic programming, where \(dp_{i, j}\) is the maximum total value on the sides facing up among cards \(1, 2, \ldots, i\), when card \(i\) belongs to the \(j\)-th chunk. The time complexity is \(O(NK)\).

posted:
last update: