Editorial for WC '17 Contest 4 S2 - Strange Travels


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.

The sanctums and portals form a directed, unweighted graph with N nodes and M edges. For each artifact i, we'll need to compute the shortest distance D1i from node 1 to node Si, as well as the shortest distance D2i from node Si to node 1. If D1i or D2i are infinite for any i (in other words, if no paths exist connecting those nodes), then we should output -1. Otherwise, the answer will be the sum of D11K and D21K.

Computing all of the shortest distances D11K can be done in O(N+M) time with a standard application of breadth-first search (BFS), starting from node 1.

However, computing the shortest distances D21K may be more problematic. We could initiate a separate breadth-first search starting from each node S1K, but that approach would be too slow to receive full marks, having a time complexity of O(K(N+M)). We can instead imagine an alternate version of the graph in which the directions of all edges are reversed (known as the transpose graph). Performing a single breadth-first search on the transpose graph starting from node 1 can allow us to compute all of the shortest distances D21K in just O(N+M) time as well.


Comments

There are no comments at the moment.