公式

D - Many Easy Optimizations 解説 by evima


Let’s consider solving the problem for a fixed \(k\).

We can assume without loss of generality that \(A_i \leq B_i\). We can rephrase the problem as choosing one of the endpoints from the interval \([A_i, B_i]\).

First, let’s try both options for \(C_1\), choosing either \(A_1\) or \(B_1\).

For any \(i\) such that the interval \([A_i, B_i]\) does not include \(C_1\), the optimal choice for \(C_i\) is uniquely determined. Once \(C_i\) is fixed, it may uniquely determine \(C_j\) for other intervals as well. We repeat this process as much as possible.

After this procedure, if we denote the minimum and maximum values of the already fixed \(C\) as \(m\) and \(M\), respectively, we can confirm that for the intervals where \(C_i\) is not yet determined, the following condition holds:

  • \(A_i \leq m \leq M \leq B_i\).

Now, for the remaining intervals, if some intervals are contained within another, we can ignore the inner intervals. Specifically, if intervals \(i\) and \(j\) satisfy:

  • \(A_i \leq A_j \leq B_j \leq B_i\)

Then, it is optimal to set \(C_j = A_j\) if \(C_i = A_i\), and set \(C_j = B_j\) if \(C_i = B_i\), so we can ignore the inner intervals.

Since we have determined that we can ignore nested intervals, all the remaining undecided intervals are overlapping intervals. Denote the remaining intervals as \((L_1, R_1), \ldots, (L_x, R_x)\). We can express them as:

  • \(L_1 \leq L_2 \leq \ldots \leq L_x \leq m \leq M \leq R_1 \leq R_2 \leq \ldots \leq R_x\).

At this point, finding the minimum cost is straightforward, and the answer is \(\min(\min_{i=1,2,\ldots,x-1}(R_{i}-L_{i+1}), M-L_1,R_x-m)\).

Using the above discussion, we can easily handle the case where \(k\) varies.

The information we need to manage is the set of overlapping intervals \(\{ (L_1, R_1), \ldots, (L_x, R_x) \}\) and the minimum value of \(R_i - L_{i + 1}\).

When \(k\) increases by \(1\), the only changes are additions or deletions of intervals to the set. Therefore, by managing the set of intervals and the set of \(R_i - L_{i + 1}\) using data structures like std::set, we can efficiently handle the updates.

The time complexity is \(\mathrm{O}(N \log N)\).

投稿日時:
最終更新: