Editorial for OTHS Coding Competition 4 P5 - Teleport
Submitting an official solution before solving the problem yourself is a bannable offence.
Authors:
,Subtask 1
Since there are no teleporters, all paths visit the same, and thus maximal, number of cells: .
Time Complexity:
Subtask 2
Let a cell be "marked" if it is between two teleporters (i.e. there exists a teleporter
at
where
and
, and also a teleporter
at
where
and
).
Claim: It is possible to visit all marked cells.
Proof: We can go to teleporter , teleport to teleporter
, then go back to teleporter
, and continue doing this until we visit all cells between them since we can use the teleporters an infinite number of times. We can also teleport to other teleporters, allowing us to visit any cell between two teleporters.
We can find the number of marked cells by iterating through every pair of teleporters and marking all cells between them using a 2D difference array. The time complexity of this is .
We then find the longest path from to a marked cell, and the longest path from a marked cell to
, using dynamic programming. The time complexity of this is
.
The answer will be (sum of the two longest paths + number of marked cells,
), as we still need to consider the cases without teleporters.
Time Complexity:
Subtask 3
To optimize our time complexity, we must optimize our marking algorithm. Two possible approaches will be explained here.
Option 1: Create a 2D prefix sum array containing all teleporters. For each cell, we can now check in whether there is a teleporter on the top-left and on the bottom-right of it.
Option 2: Use dynamic programming. Let if there exists a teleporter on the top-left of
. The base cases are cells with a teleporter, and the transition is
OR
. We apply the same logic in reverse to check if there is a teleporter on the bottom-right of
.
Time Complexity:
Alternate Solution
Model the grid as a directed graph, where nodes represent cells in the grid. To model all possible teleports, we pick an arbitrary teleporter (if there are any), and call it the main teleporter. Then, create bidirectional edges between the main teleporter and every other teleporter.
We now have an accurate graph representation of the grid. Use Tarjan's algorithm (or any other SCC algorithm) to get the condensation of the graph, which is guaranteed to be acyclic. Then, use dynamic programming to find the longest path in this new graph.
Time Complexity:
Note that this solution is not practical due to the massive constant factors involved in creating the graph and its condensation. It is only presented for theoretical purposes and will require significant optimization to pass subtask .
Comments