Donut Drone

Simulate a drone on a toroidal grid where each step moves to the highest of three rightward neighbors, handling up to 1e9 steps per move query and elevation updates.

Hard8SimulationBinary searchPrefix sumImplementationNo attempts yetTime limit8sMemory limit512 MB

Problem

You are building a simulation of a drone that explores a donut shaped planet. The drone moves over a toroidal grid, a rectangular grid that wraps around in both directions. The grid has rr rows numbered 11 to rr from top to bottom and cc columns numbered 11 to cc from left to right. Every cell has an elevation, and an elevation is a positive integer.

A toroidal grid

The drone starts in the cell in row 11 and column 11. In each step the drone looks at three cells: the cell directly to the right, the cell diagonally right and down, and the cell diagonally right and up. Row and column numbers wrap around, so row 11 is below row rr and column 11 is to the right of column cc. The drone flies to the cell with the largest elevation among the three.

Two kinds of events happen during the simulation.

  • move k: the drone takes kk steps.
  • change a b e: the elevation of the cell in row aa and column bb becomes ee.

Find the position of the drone right after each move event.

At every point in time, any three circularly consecutive cells of one column have pairwise different elevations, so the target of each step is always a single cell.

The path of the drone in the two move events of the second sample input

Input

The first line has two integers rr and cc (3r,c20003 \le r, c \le 2000), the number of rows and the number of columns of the grid. The ii-th of the next rr lines has cc integers ei,1,ei,2,,ei,ce_{i,1}, e_{i,2}, \ldots, e_{i,c} (1ei,j1091 \le e_{i,j} \le 10^9), the initial elevations of the cells in row ii.

The next line has an integer mm (1m50001 \le m \le 5000), the number of events. The jj-th of the next mm lines has the jj-th event. An event is either move k with 1k1091 \le k \le 10^9, or change a b e with 1ar1 \le a \le r, 1bc1 \le b \le c and 1e1091 \le e \le 10^9.

Output

Print one line for each move event of the input, in the order the events appear. The line for the jj-th move event has the row number and the column number of the cell where the drone stands right after that event, separated by one space.