Official

E - Wish List Editorial by en_translator


Given a fixed set of all items to buy, \(B_1, B_2, \ldots, B_K\), what is the minimum expense required to buy these \(K\) items in an appropriate order?

When buying item \(B_i\), if you have already bought \(x\) items among \(B_1, B_2, \ldots, B_{i-1}\), Item \(B_i\) is “the item with \((B_i-x)\)-th smallest item number among the unsold items,” so buying \(B_i\) costs \((A_{B_i} + C_{B_i-x})\) yen. Since \(x\) is between \(0\) and \(i-1\), the cost of buying item \(B_i\) is at least

\[A_{B_i} + \mathrm{cost}(B_i, i-1) \tag{1}\]

(where \(\mathrm{cost}(i, j) \coloneqq \min\lbrace C_{i-j}, \ldots, C_{i-2}, C_{i-1}, C_{i}\rbrace\)).

Thus, buying all of Items costs at least

\[\sum_{i = 1}^k (A_{B_i} + \mathrm{cost}(B_i, i-1)) \tag{2}\]

yen. In fact, this lower bound is achievable. Indeed, it can be achieved by repeatedly buying the item whose current cost achieves the lower bound (1), with the maximum item number.

Therefore, this problem boils down to minimizing the value of expression (2) so that the set of items to buy, \(B_1, B_2, \ldots, B_K\), contains all the items that Takahashi wants.

Now let us determine for each \(i = 1, 2, \ldots, N\) whether to buy Item \(i\) or not. Then, every time you decide to buy Item \(i\), an additional cost of \(A_i + \mathrm{cost}(i, j)\) yen is incurred, where \(j\) is the number of items that you will buy among Items \(1, 2, \ldots, i-1\). We use this fact to solve it with Dynamic Programming (DP). Specifically, let

\(\mathrm{dp}[i][j] = \) (minimum total cost required to buy \(j\) items chosen out of the first \(i\) items),

and for each \(i\) and \(j\), do the following transitions:

  • \(\mathrm{dp}[i+1][j+1] \leftarrow \min\lbrace \mathrm{dp}[i+1][j+1], \mathrm{dp}[i][j] + \mathrm{cost}(i+1, j) \rbrace\), corresponding to choosing Item \((i+1)\); and
  • \(\mathrm{dp}[i+1][j] \leftarrow \min\lbrace \mathrm{dp}[i+1][j], \mathrm{dp}[i][j] \rbrace\), corresponding not to choosing Item \((i+1)\).

Note that the latter transition should not be done if Item \((i+1)\) is in his wish list.

The entire problem can be solved in a total of \(O(N^2)\) time by precalculating entire \(\mathrm{cost}(\cdot, \cdot)\) in an \(O(N^2)\), using the relation \(\mathrm{cost}(i, j) = \min\lbrace \mathrm{cost}(i, j-1), C_{i-j} \rbrace\).

posted:
last update: