IOI 2009 - Mecho
Time Complexity: O(N²log(N²))
Algorithms used: Binary Search, BFS
An N * N grid is given in which Mecho (a bear) needs to reach his cave before the bees get him. He wants to leave his position at the last possible moment. Mecho can move to the squares above, below, left and right of him, if it is a grassy patch. The bees follow the same rules. The bees spread from square to square, whereas Mecho moves from square to square. Mecho can enter his cave, but the bees cannot.
This problem can be represented as a graph problem, where the squares are nodes in a graph, and edges are drawn between grassy patches.
Assuming that Mecho can reach his cave before the bees, it is guaranteed that Mecho can do this if he waits for any time between 0 and x. Here, the optimal answer would be x, since he wants to wait at the last possible moment. Any waiting time greater than x would allow the bees to catch Mecho.
From this observation, we find out that we can binary search on the waiting time to find the latest possible leaving time. For a waiting time x, we check if Mecho can reach his cave before the bees. If he can, then binary search on numbers greater than x, otherwise, binary search on numbers left of x. Do this until we are left with a single waiting time.
To see if Mecho can reach his cave before the bees, he needs to have a path on which every square is a grassy patch, and is reachable by Mecho before the bees.
Run one BFS for the bees, and record the time taken for the bees to reach every possible nodes in the graph. Then run another BFS for Mecho, where a node will only be visited if it is a grassy patch and the bees took more time reach the node than Mecho. If both these conditions are fulfilled, then we can say that Mecho reached the node before the bees. At the end of the BFS, check if Mecho reached any of the four node surrounding his cave. If he did, then Mecho successfully reached the cave when he waited for x time. Otherwise, Mecho will have to wait for less than x time.
Output the maximum waiting time found out by the binary search. If Mecho cannot reach the cave even when he waited for 0 time, then there is no path from his starting position to the cave. In this case, output -1 to indicate this.
Comments