Spirals
Time limit1sMemory limit64 MB
K spirals walk outward with run lengths 1,1,2,2,... on an N by M grid; for each cell print the earliest step any spiral reached it, within a 10^100 step limit.
- Level
Medium6 of 10
- Topics
- Implementation, Simulation, Math, Array
- Solved
- No attempts yet
Problem
There is a table with rows and columns. The table starts empty, and spirals are placed on it. Each spiral starts moving from its own starting cell, turning either clockwise or counter-clockwise.
One spiral moves by the following rules.
- In step 1 the spiral is on its starting cell.
- After that it walks straight runs one after another. The run lengths are in that order, and a run of length is single-cell moves in the same direction.
- The first run goes up, that is, toward smaller row numbers.
- The direction turns once at the end of every run. A clockwise spiral repeats up, right, down, left. A counter-clockwise spiral repeats up, left, down, right.
All spirals move at the same time, and each of them advances one cell per step. A spiral sometimes leaves the table and comes back inside it later.
After exactly steps, the value of each cell is the number of the earliest step in which some spiral stood on that cell.

Image 1: a spiral moving counter-clockwise

Image 2: a spiral moving clockwise
Input
The first line contains , () and ().
Each of the next lines contains integers , and (, , ). and are the row and the column of the starting cell of the -th spiral. means clockwise and means counter-clockwise. No two spirals share a starting cell.
Output
Print lines with numbers each, separated by single spaces. The -th number on the -th line is the value of the cell in row and column .
Note
The third example is explained by the picture below.

To make the picture easier to read, the letter A is attached to the numbers left by the first spiral and the letter B to the numbers left by the second spiral. Only the first 20 steps of the first spiral and the first 21 steps of the second spiral are drawn. The gray cells are the cells of the table. The other cells lie outside the table and are drawn to show how the spirals move outside it.