#P14036. [PAIO 2025] Rooks

[PAIO 2025] Rooks

题目背景

DO NOT include rooks.h. Submit using C++ >=17.

题目描述

You are given an N×MN \times M matrix AA where each element from 11 to N×MN \times M appears exactly once. You are given a rook that is on the cell that contains the element with value 11. You are also given a KK.

The rook can jump from a cell (r,c)(r,c) to a cell (r,c)(r',c') if both of the following conditions hold:

  • (r,c)(r,c)(r,c) \neq (r',c'), so we have to move to a different cell,
  • either r=rr=r' or c=cc=c', so we move only in one row or one column,
  • 0<A[r][c]A[r][c]K0 < A[r'][c'] - A[r][c] \leq K.

Find for each cell of the matrix the minimum number of moves it takes the rook to reach it from the cell containing 11, or if it is not reachable at all.

Implementation Details

You need to implement the following function:

int32 [][] calculate_moves(int32 [][] A, int32 K)
  • AA: array of length NN of arrays of length MM describing the board.
  • KK: the movement constraint.
  • The function should return an array of length NN of arrays of length MM containing the minimum number of moves needed to reach that cell from cell 11. If a cell is unreachable, the value for that cell should be equal to 1-1.

提示

Examples

Example 1

Consider the following call:

calculate_moves(
    [[8, 2, 4, 20, 5],
     [14, 13, 1, 19, 7],
     [15, 18, 12, 6, 11],
     [10, 9, 3, 16, 17]])

We have N=4,M=5,K=5N=4, M=5, K=5.

The cell containing 11, which we start from, is A[1][2]A[1][2]. Therefore in the array RR returned by calculate_moves, value R[1][2]R[1][2] should be equal to 00, as we don't need to make any moves to reach that cell.

To reach A[3][0]=10A[3][0]=10, we can go from A[1][2]=1A[1][2]=1 to A[0][2]=4A[0][2]=4 (as they are in the same column, and 41=354-1=3 \leq 5), then from A[0][2]=4A[0][2]=4 to A[0][0]=8A[0][0]=8 (as they are in the same row, and 84=458-4=4 \leq 5), then finally from A[0][0]=8A[0][0]=8 to A[3][0]=10A[3][0]=10 (as they are in the same column and 108=210-8=2). Therefore in the array RR, value R[3][0]R[3][0] should be equal to 33.

Notice that it is not possible to reach A[0][1]=2A[0][1]=2 in any way, so the value R[0][1]R[0][1] should be equal to 1-1.

The procedure should return:

[[2, -1, 1, 6, 2],
 [4, -1, 0, 5, 3],
 [4, 5, 5, -1, 4],
 [3, -1, 1, -1, -1]]

Sample Grader

Input format:

N M K
A[0][0] A[0][1] ... A[0][M-1]
A[1][0] A[1][1] ... A[1][M-1]
...
A[N-1][0] A[N-1][1] ... A[N-1][M-1]

Output format:

R[0][0] R[0][1] ... R[0][M-1]
R[1][0] R[1][1] ... R[1][M-1]
...
R[N-1][0] R[N-1][1] ... R[N-1][M-1]

Here, RR is the array returned by calculate_moves.

Constraints

  • 1N,M25001 \leq N, M \leq 2500
  • 1KNM1 \leq K \leq N \cdot M
  • 1A[i][j]NM1 \leq A[i][j] \leq N \cdot M
  • Each integer from 11 to NMN \cdot M appears in AA exactly once.

Subtasks

Subtask Score Additional Constraints
1 9 N=1N=1
2 15 N,M100N,M \leq 100
3 11 K=1K=1
4 19 K=NMK=N \cdot M
5 15 N,M500N,M \leq 500
6 31 No further constraints.