Editorial for WC '18 Contest 3 S2 - Gym Tour
Submitting an official solution before solving the problem yourself is a bannable offence.
There are two possibly optimal strategies:
- Never Fly, just visit all of the gyms by walking
- Walk directly to town , and then visit all of the gyms while Flying freely
We'll evaluate the minimum amount of time required to execute each strategy, and then use the faster one.
In order to evaluate strategy 1, we can think of the network of towns and roads as a rooted tree with nodes (one for each town), rooted at node . Now, let's first consider a variation in which Team Rocket is required to return to node at the end. In this variation, for each node (aside from the root) such that there's at least one gym anywhere in 's subtree, Team Rocket will need to walk down from 's parent to once, and then walk back up from to 's parent once. In other words, the number of days required is equal to two times the number of such nodes . The only difference between this variation and the actual strategy is that Team Rocket will save returning from their last visited gym to node , which takes a number of days equal to the depth of that gym in the tree. Therefore, to save as much time as possible, they should visit the deepest gym last. This means that, to evaluate strategy 1, we only need to determine the number of nodes whose subtrees contain at least one gym as well the maximum depth of any gym, both of which can be found by recursively traversing the tree in time.
In order to evaluate strategy 2, we can make a similar observation: for each node (aside from the root) such that its subtree contains either at least one gym or node , Team Rocket will need to walk down from 's parent to once, and that's it. Therefore, this strategy can be solved very similarly to strategy 1, by counting the number of such nodes recursively. It's possible to even reuse the same recursive function for both strategies.
Comments