Editorial for WC '16 Contest 1 S2 - Alucard's Quest
Submitting an official solution before solving the problem yourself is a bannable offence.
Alucard actually has very little choice. In order to reach each chamber that contains an item, Alucard must necessarily pass through all of the passageways between that chamber and the chamber at some point. Furthermore, he never has a reason to pass through any of the remaining passageways (those which are not between the
chamber and any chamber containing an item). Therefore, it's clear exactly which set of chambers and passageways Alucard should pass through at least once, regardless of the order in which he collects the
items.
For a given chamber , let's try to determine if Alucard will have to visit it. Let
be
if he will, and
otherwise. If chamber
contains an item itself, then certainly
. Otherwise, if we model the castle as a tree rooted at the
chamber, then
if and only if
for at least one child
of chamber
. This is because, in order to reach chamber
, Alucard will have to pass through chamber
.
How does this translate into the amount of magic power required in total?
For each chamber such that
and
, Alucard will need to use the passageway between
and its parent at some point. Therefore, assuming we can compute the
values, we can add up then add up the monster counts in these passageways connecting chambers which must be visited to yield the answer.
What remains is computing the values.
is computed based on chamber
and the
values of
's children, meaning we can recursively compute it starting from the
chamber. For convenience, we can pass in the index of
's parent in the recursive call so that we can determine which of its neighbours are its children when iterating over them.
We can also tally up the total answer during this process, rather than iterating over all nodes with true values afterwards.
Since each of the chambers is visited only once in the recursion, the algorithm has a time complexity of
.
Comments