#P7186. [CRCI2008-2009] TABLICA

[CRCI2008-2009] TABLICA

Description

Xiao Q has an N×NN \times N table. If N=4N = 4, then he fills 11 into the cell in row 11, column 11, 22 into row 11, column 22, \cdots, 55 into row 22, column 11, \cdots, 1515 into row 44, column 33, and 1616 into row 44, column 44.

Now, Xiao Q performs the following operations on the table:

  1. Shift a row: shift all cells in a row to the right, so that the number in the last column moves to the first column.

  2. Shift a column: shift all cells in a column downward, so that the number in the last row moves to the first row.

Xiao Q wants to move a number XX to the cell (R,C)(R, C), so he performs the following steps:

  • When XX is not in column CC, shift the row that contains XX.
  • When XX is not in row RR, shift the column that contains XX.

Below is an example of how to move the number 66 to the cell (3,4)(3, 4).

Xiao Q wants to move KK numbers. What is the minimum number of operations needed?

Input Format

The first line contains two positive integers NN and KK, representing the table size and the number of moves.

In the next KK lines, each line contains:

  • Three integers X,R,CX, R, C, as described above.

Output Format

Output KK lines in total. For each query:

  • Output the minimum number of moves needed.
4 1
6 3 4

3
4 2
6 3 4
6 2 2 

3
5
5 3
1 2 2
2 2 2
12 5 5

2
5
3

Hint

Constraints

For 100%100\% of the testdata: 2N1042 \le N \le 10^4, 1K1031 \le K \le 10^3, 1XN21 \le X \le N^2, 1R,CN1 \le R, C \le N.

Notes

  • The full score for this problem is 100100 points.
  • This problem is translated from COCI2008-2009 CRCI2008-2009 TABLICA, translator
    https://www.luogu.com.cn/user/219791

Translated by ChatGPT 5