If , then iff there is a key of type in a box of type . for every palidrone by Cauchy-Schwarz inequility.
Denote by the number of boxes of type and the total number of keys of type (including the keys you start with and keys in boxes).
Theorem. All box can be opened iff for every , and there is a directed path from to in graph .
Proof.
()
If , then we don’t have enough keys of type to open all boxes of type .
If there is no path from to , then it means we are unable to get any key of type .
()
We prove this by induction on the number of boxes. Denote by the number of boxes.
Assume for every , and there is a directed path from to in graph .
Case :
Then all vertices in are leaves except and the type of the only box. So there must be an edge from 0 to the type of the box.
Case :
Suppose the theorem holds for the case with boxes.
There are at least one . Consider we open a box of type (that contains a key of type if possible). Assume we destroy the key and the box just opened, then we have a setting of boxes. In this setting, we still have for all . Let be the directed graph of this -box setting.
If , then all children of in become children of , can still reach all other types in .
Assume .
If , then we can open a box of type that contains a key of type .
Otherwise, because , we still hold at least one key of type after we open a box of type (and destroy the key).
Either way, . Therefore, for every child of in , either
1. (if a key of type is in the box we just opened), or
2. and so there is a path from to and then to .
So can still reach very vertex in .
By induction hypothesis, the remaining can also be opened.
By the proof of the theorem, there is a simple algorithm to open all boxes: open any box unless you have just one key of that type and box does not contain a key that can open itself.
However, this algorithm may not yield a "lexicographically smallest" way to open the boxes.
The solve the problem, you should open the box with smallest number such that either this box is the last one of type or there is still a way to get a type key.