E - Opening Magical Box Editorial
by
Lulusphere
Editorial for printing
At any moment, the next spell is uniformly chosen among the spells that have not been opened yet. Therefore, when we try the remaining spells, it is optimal to try them in increasing order of mana cost.
Sort the mana costs as
\[ C_1 \le C_2 \le \cdots \le C_N. \]
We compute the expected contribution of each spell separately. By linearity of expectation, the answer is the sum of these contributions.
Consider spell \(i\), whose cost is \(C_i\). There are three types of times when this spell is tried.
First, it is tried exactly once when it is actually opened. This contributes
\[ C_i. \]
Second, it may be tried and fail before opening a more expensive spell. For each \(j>i\), if spell \(j\) appears before spell \(i\) in the actual order, then spell \(i\) is tried once before spell \(j\) and fails.
This happens with probability \(\frac12\), so the expected contribution of this case is
\[ C_i \cdot \frac{N-i}{2}. \]
Third, a spell that has already been opened may have to be tried again.
Consider three distinct spells \(x,a,b\), where \(a\) is cheaper than \(b\). If their actual order is
\[ x \rightarrow b \rightarrow a, \]
then when we try to find \(b\), we first try \(a\) because \(a\) is cheaper. This attempt fails, so we have to start again from the beginning, and the already opened spell \(x\) is tried once more.
For fixed \(x,a,b\), the probability that they appear in the order
\[ x \rightarrow b \rightarrow a \]
is \(\frac16\).
Now fix spell \(i\) as \(x\). Among the remaining \(N-1\) spells, the pair \(a,b\) can be chosen in
\[ \binom{N-1}{2} \]
ways. Therefore, the expected number of times spell \(i\) is tried again in this way is
\[ \frac16\binom{N-1}{2} = \frac{(N-1)(N-2)}{12}. \]
Hence, the total expected contribution of \(C_i\) is
\[ C_i\left( 1+\frac{N-i}{2} +\frac{(N-1)(N-2)}{12} \right). \]
Summing this over all \(i\), the answer is
\[ \sum_{i=1}^{N} C_i\left( 1+\frac{N-i}{2} +\frac{(N-1)(N-2)}{12} \right). \]
Thus, after sorting the costs, we can compute the answer directly using the above formula.
The time complexity is \({\cal O}(N \log N)\).
posted:
last update:
