Under construction

Still being built. Things may change

Cornfield

Interview

Time limit1sMemory limit1024 MB

Summary
Given a grid of distinct values, repeatedly harvest the largest-valued cell reachable from the border through already harvested cells, and print the first K positions in order.
Level

Medium4 of 10

Topics
Heap, Greedy, Simulation
Solved
No attempts yet

Problem

The owner of a cornfield, Minseok, wants to harvest the corn he grew carefully over the year. The field is a grid with NN rows and MM columns, and each cell has one corn plant. Minseok measured the value of each plant and assigned distinct integers 1,2,⋯ ,N×M1,2,\cdots ,N\times M.

Minseok starts outside the field. While moving outside the field, he can harvest the corn in any cell adjacent to the outside. Or, inside the field, he can move only through cells where he has already harvested corn, and harvest the corn in the cells directly above, below, left, or right of his current cell.

To control corn production, Minseok harvests only KK plants. He repeats KK times the process of harvesting the most valuable corn among the plants he can currently harvest. Find the positions of the plants he harvests, in order.

Input

The first line contains integers NN and MM (1≤N,M≤1 0001 \le N, M \le 1\,000), separated by a space.

From the second line onward, the next NN lines each contain MM integers separated by spaces. The jj-th integer on the ii-th line, aija_{ij} (1≤aij≤N×M1 \le a_{ij} \le N \times M), is the value of the corn in row ii, column jj of the grid.

The last line contains an integer KK (1≤K≤min⁡(N×M,100 000)1 \le K \le \min(N \times M, 100\,000)).

Output

Print KK lines. Each line contains the position i,ji, j (1≤i≤N1 \le i \le N, 1≤j≤M1 \le j \le M) of the corn Minseok harvests, in order. Here ii is the row and jj is the column of the grid.

Examples2

  1. Example 1

    Input
    4 5
    1 18 2 3 4
    12 17 15 20 5
    11 14 19 13 6
    10 9 16 8 7
    6
    
    Expected output
    1 2
    2 2
    4 3
    3 3
    2 3
    2 4
    
  2. Example 2

    Input
    3 3
    9 8 1
    4 5 2
    6 3 7
    4
    
    Expected output
    1 1
    1 2
    3 3
    3 1