Source: CGMO-2017-P8
Category: Operations and Strategies

Problem: Given an integer $n \\geq 2$. Let the grid tables \n$A = \\begin{pmatrix} a_{11} & a_{12} & \\cdots & a_{1n} \\\\ a_{21} & a_{22} & \\cdots & a_{2n} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ a_{n1} & a_{n2} & \\cdots & a_{nn} \\end{pmatrix}, \\quad B = \\begin{pmatrix} b_{11} & b_{12} & \\cdots & b_{1n} \\\\ b_{21} & b_{22} & \\cdots & b_{2n} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ b_{n1} & b_{n2} & \\cdots & b_{nn} \\end{pmatrix}$ \nsatisfy $\\{a_{ij} \\mid 1 \\leq i,j \\leq n\\} = \\{b_{ij} \\mid 1 \\leq i,j \\leq n\\} = \\{1, 2, \\cdots, n^2\\}.$ \nThe following operation can be performed on $A$: select two numbers in the same row or the same column, swap their positions, while the remaining $n^2 - 2$ numbers remain unchanged. This operation is called a transposition. \nFind the smallest positive integer $m$ such that for any $A, B$, it is always possible to transform $A$ into $B$ through at most $m$ transpositions.

Answer: $2n^{2}-2n$

Reference solution:
First, consider the one-dimensional problem: let arrays $X=(x_1,x_2,\dots,x_m)$ and $Y=(y_1,y_2,\dots,y_m)$ be permutations of the same $m$ elements. Then $X$ can be transformed into $Y$ by at most $m-1$ swaps. In fact, for $i=1,2,\dots,m-1$, we can sequentially swap the element $y_i$ into the $i$-th position of $X$; after $m-1$ such swaps, the $m$-th entry must naturally be $y_m$.

For the two-dimensional problem, since the allowed operations (row and column transpositions) are invariant under relabeling the elements, we can assume without loss of generality that the target matrix is the standard row-major table:
$$B=\begin{pmatrix}
1&2&\cdots&n\\
n+1&n+2&\cdots&2n\\
\vdots&\vdots&\ddots&\vdots\\
n^2-n+1&n^2-n+2&\cdots&n^2
\end{pmatrix}.$$

We first prove that any matrix $A$ can be transformed into $B$ by at most $2n^2-2n$ transpositions. We begin by showing a more general claim: for any $m \le n$, any $m$ specified target elements located in $m$ columns can be moved to the first row of these $m$ columns in a specified target permutation using at most $2m-1$ transpositions, without changing the positions of any elements outside these $m$ columns. We proceed by induction on $m$.
When $m=1$, the statement is obvious: $1$ element in $1$ column can be moved to the first row of that column by at most $1$ column transposition, and $1 \le 2(1)-1$.
Assume the claim holds for $m-1$, and consider the case $m$.
**Case 1:** If each of the $m$ columns contains exactly one of the $m$ target elements, then we can first move the $m$ elements to the first row by at most $m$ column transpositions. Then, by the one-dimensional problem, we can sort them into the target permutation using at most $m-1$ row transpositions within the first row. Hence at most $m+(m-1)=2m-1$ transpositions are needed.
**Case 2:** If there exists a column $k$ among the $m$ columns that does not contain any of the $m$ target elements, let $x$ be the element whose target position is the first row of column $k$. Since column $k$ does not contain $x$, $x$ is in some other column among the $m$ columns. Swap $x$ into column $k$ (via a row transposition) and then swap it into the first row (via a column transposition). Since column $k$ initially contained none of the $m$ elements, the elements swapped with $x$ are not among the $m$ target elements, so these two transpositions do not change the positions of the remaining $m-1$ target elements. After removing column $k$ from consideration, the induction hypothesis gives that we can finish placing the remaining $m-1$ elements with at most $2(m-1)-1 = 2m-3$ more transpositions. Thus we need at most $2+(2m-3)=2m-1$ transpositions. The induction is complete.

Applying this claim for $m=n$, the first row of $A$ can be turned into the first row of $B$ (i.e., $(1,2,\dots,n)$) by at most $2n-1$ transpositions.
Similarly, for each $i$ with $2\le i\le n-1$, we can treat the subgrid consisting of rows $i$ through $n$ as a new grid. The target elements for row $i$ are all located in this subgrid. By the same logic, the $i$-th row of $A$ can be turned into the $i$-th row of $B$ by at most $2n-1$ transpositions. Because these transpositions are performed entirely within the subgrid (i.e., row transpositions within rows $\ge i$, and column transpositions between rows $\ge i$), they do not disturb the already fixed rows $1$ through $i-1$.
At this point, the $n$-th row of $A$ is a permutation of $n^2-n+1,n^2-n+2,\dots,n^2$, so it can be turned into the $n$-th row of $B$ by at most $n-1$ row transpositions.
Consequently, $A$ can be transformed into $B$ by at most $(n-1)(2n-1)+(n-1)=2n^2-2n$ transpositions.

To show that $2n^2-2n$ transpositions are necessary, consider the matrix
$$A=\begin{pmatrix}
n+2&n+3&\cdots&2n&n+1\\
2n+2&2n+3&\cdots&3n&2n+1\\
\vdots&\vdots&\ddots&\vdots&\vdots\\
n^2-n+2&n^2-n+3&\cdots&n^2&n^2-n+1\\
2&3&\cdots&n&1
\end{pmatrix}.$$
Let $D$ be the number of elements in the grid that are located in a row strictly above their target row in $B$ (i.e., current row index $<$ target row index). In $A$, for $1 \le i \le n-1$, the $n$ elements in row $i$ all belong to row $i+1$ in $B$, so their current row index is less than their target row index. The elements in row $n$ belong to row $1$, so they are not above their target rows. Thus, initially exactly $n(n-1)$ elements are above their target rows, so $D = n(n-1)$. In $B$, $D = 0$.
A row transposition does not change the row index of any element, so it changes $D$ by $0$. A column transposition swaps an element in row $r_1$ with an element in row $r_2$. Assuming $r_1 < r_2$, the element at $r_1$ moves downward to $r_2$, and the element at $r_2$ moves upward to $r_1$. The element moving upward has its row index decreased; if it was already above its target row, it remains above its target row, so it cannot decrease $D$. The element moving downward can change from being above its target row to not being above its target row, which decreases $D$ by at most $1$. Therefore, $D$ decreases by at most $1$ per column transposition. Thus, at least $n(n-1)$ column transpositions are required to reduce $D$ to $0$.

Similarly, let $R$ be the number of elements in the grid that are located in a column strictly to the left of their target column in $B$. In $A$, for $1 \le j \le n-1$, the $n$ elements in column $j$ belong to column $j+1$ in $B$, so they are to the left of their target columns. The elements in column $n$ belong to column $1$. Thus, initially $R = n(n-1)$. In $B$, $R = 0$.
A column transposition does not change the column of any element, so it changes $R$ by $0$. A row transposition swaps two elements in the same row, moving at most one element to the right, so it can decrease $R$ by at most $1$. Therefore, at least $n(n-1)$ row transpositions are required to reduce $R$ to $0$.

Since column transpositions do not decrease $R$ and row transpositions do not decrease $D$, the total number of transpositions must be at least the sum of the minimum required column and row transpositions. This requires at least $n(n-1) + n(n-1) = 2n^2 - 2n$ transpositions.

Thus, the smallest positive integer $m$ is $2n^2-2n$.

Grading guidelines:
(Partial) 1. Observed that one can assume WLOG that the target table is the standard row-major table $B$ (relabeling/invariance argument). 2. Proved the 1D lemma: any permutation of $m$ elements can be transformed into any other using at most $m-1$ swaps (and applied it correctly to a row). 3. Established a correct lower-bound invariant for some explicit “shifted” matrix $A$, e.g. defining $D$ (elements above their target row) or $R$ (elements left of their target column) and showing that one type of transposition does not change it while the other decreases it by at most 1, hence needing at least $n(n-1)$ transpositions of that type. (Almost) 1. Gave a complete upper-bound strategy leading to $2n^2-2n$ (e.g. the induction claim giving $2m-1$ to place $m$ targets in $m$ columns, then applying it row-by-row), but with a minor gap such as not fully justifying that previously fixed rows are not disturbed or not fully proving the induction step in Case 2. 2. Gave the correct extremal example matrix and essentially the full lower-bound argument $D$ and $R$ leading to $2n^2-2n$, but with a localized mistake (e.g. unclear why a column transposition decreases $D$ by at most 1, or why the required row/column transpositions add without interference). 3. Solution reaches the correct value $m=2n^2-2n$ with the main ideas present, but has a small number of boundary cases unchecked (e.g. handling the last row requiring only $n-1$ row swaps, or treating $n=2$ separately).

Construction task:
Provide exactly one explicit 10x10 integer matrix A as a single Python expression (Python-literal-friendly), such that evaluating it yields a nested list of 10 lists each of length 10. The entries of A must be exactly the integers 1 through 100, each appearing once. A legal transposition is swapping two entries in the same row or in the same column. Let the target matrix B be the 10x10 row-major matrix with entries 1,2,...,100. Your constructed A must be such that the minimum number of legal transpositions required to transform A into this B attains the maximum possible value among all such A for n=10. Put only the Python expression inside <construct>...</construct> and nothing else.

Reference construction:
[[((r + 1) % 10) * 10 + ((c + 1) % 10) + 1 for c in range(10)] for r in range(10)]

Verifier code:
import sys

def fail(msg):
    print(msg)
    sys.exit(0)

def safe_eval(expr: str):
    allowed_builtins = {
        "range": range,
        "len": len,
        "list": list,
        "int": int,
    }
    env = {"__builtins__": allowed_builtins}
    return eval(expr, env, {})

def main():
    s = sys.stdin.read()
    if not s.strip():
        fail("Parsing error: empty input.")
    try:
        obj = safe_eval(s)
    except Exception as e:
        fail(f"Parsing error: {e}")

    # Dimension/type checks
    if not isinstance(obj, list):
        fail("Dimensions error: top-level object is not a list.")
    if len(obj) != 10:
        fail(f"Dimensions error: expected 10 rows, got {len(obj)}.")
    for i, row in enumerate(obj):
        if not isinstance(row, list):
            fail(f"Dimensions error: row {i} is not a list.")
        if len(row) != 10:
            fail(f"Dimensions error: expected row {i} length 10, got {len(row)}.")
        for j, v in enumerate(row):
            if type(v) is not int:
                fail(f"Type error: entry at ({i},{j}) is not a strict int (got {type(v).__name__}).")

    A = obj

    # Permutation check
    flat = [A[i][j] for i in range(10) for j in range(10)]
    expected_set = set(range(1, 101))
    got_set = set(flat)
    if got_set != expected_set:
        missing = sorted(expected_set - got_set)
        extra = sorted(got_set - expected_set)
        if missing:
            fail(f"Permutation error: missing values (first few): {missing[:10]}")
        if extra:
            fail(f"Permutation error: extra values (first few): {extra[:10]}")
        fail("Permutation error: entries are not exactly a permutation of 1..100.")
    if len(flat) != len(got_set):
        # duplicates exist
        # find one duplicate
        seen = set()
        dup = None
        for v in flat:
            if v in seen:
                dup = v
                break
            seen.add(v)
        fail(f"Permutation error: duplicate value detected ({dup}).")

    # Cyclic-shift pattern check
    for i in range(10):
        for j in range(10):
            exp = 10 * ((i + 1) % 10) + ((j + 1) % 10) + 1
            if A[i][j] != exp:
                fail(
                    f"Cyclic pattern error at ({i},{j}): got {A[i][j]}, expected {exp} "
                    f"for A[i][j]=10*((i+1)%10)+((j+1)%10)+1."
                )

    # Invariant checks: D and R
    D = 0  # number of entries in a row strictly above their target row
    R = 0  # number of entries in a column strictly left of their target column
    for i in range(10):
        for j in range(10):
            v = A[i][j]
            tr = (v - 1) // 10
            tc = (v - 1) % 10
            if i < tr:
                D += 1
            if j < tc:
                R += 1
    if D != 90:
        fail(f"Invariant error: D should be 90, got {D}.")
    if R != 90:
        fail(f"Invariant error: R should be 90, got {R}.")

    print("True")

if __name__ == "__main__":
    main()