#P7186. [CRCI2008-2009] TABLICA
[CRCI2008-2009] TABLICA
Description
Xiao Q has an table. If , then he fills into the cell in row , column , into row , column , , into row , column , , into row , column , and into row , column .
Now, Xiao Q performs the following operations on the table:
-
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.
-
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 to the cell , so he performs the following steps:
- When is not in column , shift the row that contains .
- When is not in row , shift the column that contains .
Below is an example of how to move the number to the cell .

Xiao Q wants to move numbers. What is the minimum number of operations needed?
Input Format
The first line contains two positive integers and , representing the table size and the number of moves.
In the next lines, each line contains:
- Three integers , as described above.
Output Format
Output 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 of the testdata: , , , .
Notes
- The full score for this problem is points.
- This problem is translated from COCI2008-2009 CRCI2008-2009 TABLICA, translator https://www.luogu.com.cn/user/219791
Translated by ChatGPT 5
京公网安备 11011102002149号