Official

B - Mex Boxes Editorial by evima


Let us assume that the boxes show numbers also before we finish putting the balls in them. Initially, all \(K\) boxes show \(0\).

Let \(X\) denote the number of balls with \(0\). We can make at most \(\min(K, X)\) boxes show values not less than \(1\). On the other hand, for at least \(K-\min(K, X)\) boxes, we have no choice but to let them show \(0\).

We can see that, after putting balls with \(0\) in boxes, if we throw away the boxes not showing \(1\) and subtract \(1\) from the values shown by the boxes and the values written on the balls, we get the original problem again. It can also be seen that it is the number of remaining boxes that affects the final answer. We can show from this that we should keep as many boxes as possible.

In the end, we should put the balls in the boxes in ascending order of written value and make as many changes as possible to the values shown by the boxes. We can do this in \(O(N \log N)\) or \(O(N)\) time, which is fast enough for \(N \leq 3 \times 10^5\).

posted:
last update: