A Bug That's Not a Pill Bug
Time limit8sMemory limit1024 MB
Simulate a bug that turns left at obstacles and find its lattice position after it moves exactly d steps, where d can reach 10^18.
- Level
Medium5 of 10
- Topics
- Simulation, Hash map, Implementation
- Solved
- No attempts yet
Problem
A bug that looks like a pill bug is walking on a plane. A Cartesian coordinate system is defined on the plane, where the -axis points from west to east and the -axis points from south to north.
The bug starts at a lattice point (a point whose x and y coordinates are both integers) and faces the positive direction. Some lattice points have obstacles. The bug keeps moving under the following rules while avoiding obstacles.
- The bug tries to move to the adjacent lattice point in the direction it is facing.
- If that point has no obstacle, the bug moves there and keeps its direction.
- If that point has an obstacle, the bug stays where it is and turns 90 degrees to the left.
The initial position, the obstacle locations, and a distance are given. Find the position of the bug after it has moved exactly that distance.
The figures show some of the sample datasets. In the left figure, the first two datasets start at (0, 1). The bug moves to (1, 1) and then to (2, 1). Next it tries to move to (3, 1), but an obstacle is there, so it turns toward the positive direction and moves to (2, 2). Points the bug passes through are marked with orange circles. The right figure shows the next two datasets.


Input
The input has multiple datasets, each in the following format. There are at most 200 datasets.
Here is the number of obstacles, an integer from 1 to 1000. and are integers from 0 to 100, and the bug starts at . is the distance to move, an integer from 1 to . Each obstacle is at , where and are integers from 0 to 100. No two obstacles share a location, and no obstacle is at the starting point. The bug is guaranteed to be able to move distance or more in this configuration.
The input ends with a line containing a single 0.
Output
For each dataset, print two integers separated by a space on one line: the and coordinates of the bug after it has moved distance . Coordinates can be negative.