#P7975. Chess Box Placement
Chess Box Placement
Chess Box Placement
We are given a chess box with dimensions \(n \times m \times 2\) (i.e. two layers) bounded by walls on all four sides. The lower layer already contains red chess pieces, while there are exactly \(nm\) black chess pieces waiting to be placed in the upper layer. Both red and black pieces come in several types, and for each type, the number of red and black pieces is equal. Each type is labeled by its characteristic value \(v_{i,j}\) (in the input, for the red pieces, the board cell at \((i,j)\) has a value).
The black pieces must be placed one by one following a fixed given order. Suppose the indices in the chess box are defined with the top-left cell as \((1,1)\) and the bottom-right as \((n, m)\). When placing a black piece of type \(T\), you must choose an empty cell \((i,j)\) in the upper layer such that the red piece directly below (in the lower layer) is of the same type \(T\). Among all eligible cells (i.e. cells satisfying the condition), the placement is determined by the following rules:
- Choose the cell with the largest compactness, where the compactness of an empty cell \((i,j)\) is defined as the number of its four neighbors (up, down, left, right) that are either already occupied by a black piece or are walls (i.e. the cell is on the boundary).
- If multiple cells have the same maximum compactness, choose the one with the smallest \(i+j\) (i.e. the minimal sum of its coordinates).
- If a tie still exists, choose the one with the smallest row index \(i\).
Your task is: given the placement of the red pieces in the lower layer and the sequence of black pieces to be placed, determine for each cell of the upper layer the order in which the black piece was placed.
inputFormat
The first line contains two integers \(n\) and \(m\) (\(1 \leq n, m \leq 100\)), representing the number of rows and columns in the chess box.
The next \(n\) lines each contain \(m\) integers. The \(j\)th integer in the \(i\)th line is the characteristic value \(v_{i,j}\) of the red chess piece at cell \((i,j)\) in the lower layer.
The following \(nm\) lines each contain one integer. These integers represent, in order, the type of each black chess piece to be placed.
outputFormat
Output \(n\) lines. Each line contains \(m\) integers separated by spaces. The integer in the \(i\)th row and \(j\)th column indicates the order in which the black piece was placed in that upper cell.
sample
2 2
1 2
2 1
1
2
2
1
1 2
3 4
</p>