Polar Bear

Time limit5sMemory limit128 MB

Problem

This is Conway's Game of Life played on polar-coordinate graph paper instead of a rectangular grid. The board has $m$ concentric rings and $n$ radial lines. The rings are numbered from the outside inward, $0$ for the outermost ring up to $m-1$ for the innermost ring. Because each ring is divided by the $n$ radial lines, it contains exactly $n$ cells. A cell is identified by a pair $(r, c)$: its ring $r$ ($0 \le r \le m-1$) and its position $c$ ($0 \le c \le n-1$), counted clockwise from a fixed radius. The number of radial lines $n$ is always even.

At every tick all cells update simultaneously under the usual Game of Life rules: a dead cell with exactly three live neighbors becomes live in the next generation; a live cell with fewer than two or more than three live neighbors becomes dead; every other cell keeps its state.

Every cell has exactly eight neighbors, defined as follows (all position indices are taken modulo $n$):

  • An interior cell $(r, c)$ with $0 < r < m-1$ has the eight neighbors $(r, c\pm 1)$, $(r-1, c-1)$, $(r-1, c)$, $(r-1, c+1)$, $(r+1, c-1)$, $(r+1, c)$, and $(r+1, c+1)$.
  • A cell $(0, c)$ on the outer ring has the five ordinary neighbors $(0, c\pm 1)$, $(1, c-1)$, $(1, c)$, $(1, c+1)$, together with the diametrically opposite cell $(0, c + n/2)$ on the same ring and that cell's two ring neighbors $(0, c + n/2 - 1)$ and $(0, c + n/2 + 1)$.
  • A cell $(m-1, c)$ on the inner ring has the five ordinary neighbors $(m-1, c\pm 1)$, $(m-2, c-1)$, $(m-2, c)$, $(m-2, c+1)$, together with the diametrically opposite cell $(m-1, c + n/2)$ and its two ring neighbors $(m-1, c + n/2 - 1)$ and $(m-1, c + n/2 + 1)$.

Input

The input contains several test cases. Each test case begins with two positive integers $m$ and $n$ ($3 \le m \le 100$, $6 \le n \le 100$, with $n$ even), the number of rings and the number of radial lines. Next comes a positive integer $k$ followed by $k$ distinct pairs of integers (which may span several lines); each pair $r\ c$ gives the ring $r$ and position $c$ of one initially live cell. After the pairs comes a single nonnegative integer $g$ ($g \le 500$), the number of generations to simulate. The last test case is followed by a line containing two zeros, which is not processed.

Output

For each test case, print Case X: (where X is the test case number, starting from $1$) followed by five integers: the number of live cells after $g$ generations, then $r_1\ c_1$, the position of the lexicographically first live cell, and $r_2\ c_2$, the position of the lexicographically last live cell. Cells are ordered lexicographically by ring number and then by position. If no cells are alive, print 0 -1 -1 -1 -1 for those five integers.