Editorial for WC '15 Contest 4 S2 - World Tour
Submitting an official solution before solving the problem yourself is a bannable offence.
The cities and flights represent a directed graph with  nodes, each with 
 outgoing edge. For each "component" in the graph (a maximal set of nodes which would be connected to one another if the graph was undirected), the graph structure guarantees that there must be exactly one cycle, with the remaining nodes in the component connecting to that cycle (possible indirectly). An obvious solution would be to start at each node and follow the path until we have reached a node that is already visited, and then stop. Doing so for each node yields an 
 solution which is given 7/23 of the points. To improve on this, we can process one component at a time, finding its cycle and then handling all of its non-cyclic nodes.
We can iterate over the nodes from  to 
. If the answer 
 for node 
 hasn't been computed yet, then we'll process node 
's entire component right away. The first step is to locate any node which is part of the component's cycle. This can be done by repeatedly following edges forward from 
, marking nodes as having been visited, until a node 
 is reached which has already been visited – this node must be part of the cycle. Next, we need to get the cycle's size 
 (the number of nodes which are part of it). We can do this by repeatedly following edges forward from 
 until we return 
, and counting the number of nodes visited along the way.
Now, for each node  in the cycle, 
 (if Jaws starts in the cycle, he'll just visit all 
 nodes in the cycle). For each non-cyclic node 
 which is an additional distance of 
 away from any node in the cycle, 
 (Jaws will visit 
 non-cycle nodes on his way to the cycle, and then visit all 
 nodes in the cycle). As such, we can compute the answers for all nodes in the component in linear time using breadth-first search, by pushing all the nodes in the cycle onto a queue, and then expanding outwards from the cycle.
If we're processing node  and there's an edge from a non-cycle node 
 to 
, then we can set 
 and push 
 onto the queue. Note that this will require precomputing the list of incoming edges for each node. At the end, we can output the computed values 
. The total time complexity of this algorithm is 
.
Comments