E - Souvenir Editorial by spheniscine


Let’s treat the problem as a shortest path problem on a directed weighted graph. As we may have to answer queries for all possible pairs of vertices, the Floyd-Warshall algorithm, being able to find the shortest path between all pairs in \(O(N^3)\), seems to be useful here.

The question is how to choose the weights. Well, we know for every \((u, v)\) where \(S_{u, v} = \tt{Y}\), we could draw a directed edge from \(u\) to \(v\). Using this edge would add one “direct flight” to our route, but will also gain us \(A_v\) souvenir value. Let’s model the cost of a direct flight with some value \(\omega\), and since we wish to minimize direct flights primarily, but maximize souvenir value secondarily, the souvenir values should be considered as a negative cost. So the weight of the edge should be \(\omega - A_v\).

To use Floyd-Warshall, we also need some notionally “infinite” maximum distance \(\Omega\) to serve as an upper bound, so that we can detect when we should answer Impossible.

Thus, we need \(\omega > \sum_iA_i\), as one direct flight is considered to cost more than any amount of souvenir value, and we also need \(\Omega > N \cdot \omega\), so that no finite path length would “overflow” and be wrongly considered impossible. So we could use \(\omega = 10^{13}\) and \(\Omega = 10^{17}\), among many other possibilities.

After running Floyd-Warshall to obtain a distance matrix, when we answer a query for \((u, v)\), let \(d\) be the raw distance between them. We first check if \(d = \Omega\), if so, answer Impossible. Otherwise, we could obtain the number of flights needed by \(a = \lceil d / \omega \rceil\), and the souvenir value by \(b = a \cdot \omega - d + A_u\). (We need to add \(A_u\), as the souvenir at the starting city is not part of our path distance.)

posted:
last update: