#P8416. [THUPC 2022 决赛] 拯救还是毁灭

    ID: 9513 远端评测题 2000ms 512MiB 尝试: 0 已通过: 0 难度: 9 上传者: 标签>贪心2022Special JudgeO2优化构造THUPC

[THUPC 2022 决赛] 拯救还是毁灭

Problem Description

Some say it saved the world; others say it destroyed the world.

This world is on the brink of collapse! Order has already fallen into chaos.

Order can be abstracted as an n×nn \times n matrix containing a permutation of 1n21 \sim n^2. You want to save the world, so you ask God to help restore order. However, God is not all-powerful: it can only swap two numbers in the same row or in the same column of the matrix. Also, it does not know how to swap to restore the matrix and must follow your instructions.

Fortunately, you do not have to restore it using the minimum number of swaps. You only need to be no worse than the worst case. That is, if your number of swaps is kk, and among all permutations of 1n21 \sim n^2, the maximum value of the minimum required swaps is k0k_0, then you only need to satisfy kk0k \le k_0.

Note: restoring means turning the matrix into the following matrix:

$\begin{matrix} 1 & 2 & 3 & \cdots & n \\ n+1 & n+2 & n+3 & \cdots & 2n \\ 2n+1 & 2n+2 & 2n+3 & \cdots & 3n\\ \vdots & \vdots & \vdots & \ddots & \vdots \\ (n-1)n+1 & (n-1)n+2 & (n-1)n+3 & \cdots & n^2 \end{matrix}$

Input Format

The next nn lines each contain nn positive integers, describing this n×nn \times n matrix. It is guaranteed that each number in 1n21 \sim n^2 appears exactly once.

Output Format

The first line contains a non-negative integer kk, which is your number of swaps.

The next kk lines each contain four positive integers x1,y1,x2,y2x_1, y_1, x_2, y_2, meaning you swap the number at row x1x_1, column y1y_1 with the number at row x2x_2, column y2y_2.

You must guarantee that x1=x2x_1 = x_2 or y1=y2y_1 = y_2.

2
4 2
3 1

3
1 1 1 2
1 2 2 2
1 1 1 2

2
2 1
3 4

3
2 1 2 2
1 1 1 2
2 1 2 2

2
3 2
1 4

2
1 1 1 1
1 1 2 1

2
1 2
3 4

0

Hint

[Sample 1 Explanation]

It can be proven that this is one of the solutions with the minimum number of swaps, and obviously it meets the requirement.

[Sample 2 Explanation]

For this input, the plan in the sample output does not use the minimum number of swaps. However, we know there exists a permutation of 1n21 \sim n^2 (namely, the previous sample) that needs at least 33 swaps, so this plan is also valid.

[Sample 3 Explanation]

We allow the case where (x1,y1)=(x2,y2)(x_1, y_1) = (x_2, y_2).

[Sample 4 Explanation]

Note that kk can be equal to 00.

[Constraints and Notes]

It is guaranteed that 1n10001 \le n \le 1000.

It is guaranteed that each number in 1n21 \sim n^2 appears exactly once in the input matrix.

Translated by ChatGPT 5