P7975 "Stoi2033" Split

Background

> Before time notices, let me take you away. > There is no proof, and no emptiness. > Based on two stances, I will have your back. > Before time notices, let me take you away. > This is not stubbornness, and this is not escape. > Only when no one forces you to leave can you be happy. > — "Split"

Description

There is an $n \times m \times 2$ chess box (surrounded by walls) and $nm$ black pieces and $nm$ red pieces. The pieces have several types. For each type, the number of red pieces equals the number of black pieces of that type. The type of a piece is marked by a characteristic value $v_{i,j}$. Pieces with the same characteristic value are of the same type, and pieces with different characteristic values are of different types. The red pieces are placed on the lower layer of the chess box, and they have already been arranged. Now Vinsta wants to place the black pieces onto the upper layer of the chess box in a given order. Define the coordinates inside the box as: the top-left corner is $(1,1)$, the bottom-right corner is $(n,m)$, and the cell in row $i$ and column $j$ is $(i,j)$. Then each black piece placed must be put into a position that satisfies the following rules: 1. The position has no black piece, and directly below it there is a red piece of the same type as this black piece. 2. Under rule 1, if there are multiple positions, define the **compactness** of a position as the number of its four sides that are adjacent to a black piece or are a wall of the chess box. Choose the position with the maximum **compactness**. 3. Under rule 2, if there are still multiple positions, let the coordinate be $(i,j)$, and require $i+j$ to be minimum. 4. Under rule 3, if there are still multiple positions, require $i$ to be minimum. Given the arrangement of the red pieces and the order in which the black pieces are inserted, please help her find, for each position, the insertion order of the black piece placed there.

Input Format

The first line contains two integers $n, m$. The next $n$ lines each contain $m$ integers. The integer in row $i$ and column $j$ is $v_{i,j}$. The next line contains $nm$ integers, describing the type of the piece inserted each time, in order.

Output Format

Output $n$ lines each containing $m$ integers. For each position, the number $k_{i,j}$ means that the piece at $(i,j)$ is the $k_{i,j}$-th one inserted.

Explanation/Hint

For $30\%$ of the testdata, $1 \le n, m \le 70$. For another $30\%$ of the testdata, $v_{i,j} = 1$. For $100\%$ of the testdata, $1 \le n, m \le 10^3$, $1 \le v_{i,j} \le 10$, and it is guaranteed that for each type, the numbers of black and red pieces are equal. Translated by ChatGPT 5