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
nodes and
edges. For each artifact
, we'll need to compute the shortest distance
from node
to node
, as well as the shortest distance
from node
to node
. If
or
are infinite for any
(in other words, if no paths exist connecting those nodes), then we should output -1
. Otherwise, the answer will be the sum of
and
.
Computing all of the shortest distances
can be done in
time with a standard application of breadth-first search (BFS), starting from node
.
However, computing the shortest distances
may be more problematic. We could initiate a separate breadth-first search starting from each node
, but that approach would be too slow to receive full marks, having a time complexity of
. 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
can allow us to compute all of the shortest distances
in just
time as well.
Comments