Problem A
Slippery Floor
Despite his lack of skating ability, Tom always seems to find himself on an outdoor rink with his friends. Due to his poor skills Tom is unable to steer himself on skates and is only able to push himself in one of the cardinal directions (North, South, East, and West) when he crashes into an obstacle.
This outdoor rink in particular is covered in various obstacles which Tom is unable to climb over. Tom wants to know if it is possible for him to make his way to the edge of the rink to safety. Tom is able to make himself move in any cardinal direction at the start of his journey, but after that he is only capable of turning when he has collided with an obstacle.
Because Tom feels embarrassed about his inability to turn, he wants to find a route off the rink while hitting the smallest number of obstacles (if it is even possible for him to escape at all).
Luckily you happen to also be visiting the rink and brought your handy laptop nearby. Given a description of the rink, can you help Tom compute the quickest way out?
Inputs
The first line contains 5 integers $w,h,x,y,n$: $w$ and $h$ are the width and height of the ice rink respectively ($1 \leq w, h\leq 10^9$), $x$ and $y$ is Tom’s starting location ($0 \leq x < w$, $0 \leq y < h$), and $n$ is the number of obstacles on the rink ($0 \leq n \leq 10^5$). This is followed by $n$ lines each containing the location $x_i,y_i$ ($0 \leq x_i < w$, $0 \leq y_i < h$) of the $i$-th obstacle. The location of the obstacles cannot overlap with Tom’s location.
The following diagram illustrates example 4. The rink is $7 \times 6$ squared units in size and the obstacles are the blue squares on the grid. Tom begins at the location of the green circle, and the red path is the optimal way out, with red dots to indicate segments. As we can see, Tom made 4 moves, hit an obstacles 3 times, and made one last move at $(3, 4)$ to escape the rink.
Outputs
Output the minimum amount of moves Tom needs to reach the border of the rink. If Tom cannot escape the rink, output “IMPOSSIBLE”.
Sample Input 1 | Sample Output 1 |
---|---|
1 1 0 0 0 |
0 |
Sample Input 2 | Sample Output 2 |
---|---|
4 4 1 1 8 1 0 2 0 0 1 3 1 0 2 3 2 1 3 2 3 |
IMPOSSIBLE |
Sample Input 3 | Sample Output 3 |
---|---|
4 4 1 1 7 1 0 2 0 0 1 3 1 0 2 3 2 1 3 |
2 |
Sample Input 4 | Sample Output 4 |
---|---|
7 6 3 2 13 1 0 3 0 5 0 0 1 6 1 0 2 6 2 3 3 0 4 2 4 6 4 1 5 5 5 |
4 |
Sample Input 5 | Sample Output 5 |
---|---|
9 5 1 1 14 1 0 3 0 5 0 7 0 0 1 2 1 6 1 8 1 0 3 4 3 8 3 1 4 3 4 5 4 |
7 |
Sample Input 6 | Sample Output 6 |
---|---|
5 5 2 3 4 2 4 3 3 1 3 2 0 |
2 |