Editorial for WC '18 Contest 3 S2 - Gym Tour


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

There are two possibly optimal strategies:

  1. Never Fly, just visit all of the gyms by walking
  2. Walk directly to town F, 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 N nodes (one for each town), rooted at node 1. Now, let's first consider a variation in which Team Rocket is required to return to node 1 at the end. In this variation, for each node i (aside from the root) such that there's at least one gym anywhere in i's subtree, Team Rocket will need to walk down from i's parent to i once, and then walk back up from i to i's parent once. In other words, the number of days required is equal to two times the number of such nodes i. The only difference between this variation and the actual strategy is that Team Rocket will save returning from their last visited gym to node 1, 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 i 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 \mathcal O(N) time.

In order to evaluate strategy 2, we can make a similar observation: for each node i (aside from the root) such that its subtree contains either at least one gym or node F, Team Rocket will need to walk down from i's parent to i 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

There are no comments at the moment.