Source: TSTST-2024-P9
Category: Extremal Problems

Problem: "Let $n \ge 2$ be a fixed integer. The cells of an $n \times n$ table are
filled with the integers from $1$ to $n^2$ with each number appearing exactly once.
Let $N$ be the number of unordered quadruples of cells on this board
which form an axis-aligned rectangle,
with the two smaller integers being on opposite vertices of this rectangle.
Find the largest possible value of $N$."

Answer: (n^4-n^2)/12

Reference solution:
The largest possible value of $N$ is $\frac{n^2(n^2-1)}{12}$. 

Let us call an axis-aligned rectangle satisfying the condition in the problem a *wobbly* rectangle. We defer the construction until the proof of the upper bound is complete, since the proof suggests the construction.

**Proof of the upper bound:**
Call a triple of cells $(a,b,c)$ an *elbow* if $a$ and $b$ are in the same row, $b$ and $c$ are in the same column, and the values in the cells satisfy $a < b$ and $c < b$. The cell $b$ is called the center of the elbow. 

Observe that the wobbly rectangles are exactly the axis-aligned rectangles that contain exactly $2$ elbows. To see this, consider the four vertices of an axis-aligned rectangle. The two smaller integers are on opposite vertices if and only if the other two opposite vertices both have values greater than their row and column neighbors within the rectangle. These two larger vertices thus form the centers of two elbows.

**Claim.** Every axis-aligned rectangle has at least $1$ elbow.
*Proof.* Consider the cell containing the largest integer among the four vertices of any axis-aligned rectangle. The two vertices of the rectangle that share a row and a column with this largest cell must contain smaller integers. Consequently, this largest cell is the center of an elbow, as its value is greater than the values in the two adjacent vertices of the rectangle. 

Let $E$ be the total number of elbows in the grid, and let $M$ be the number of non-wobbly rectangles. Since every wobbly rectangle contains exactly $2$ elbows and every non-wobbly rectangle contains at least $1$ elbow, the total number of elbows is at least $M + 2N$. The total number of axis-aligned rectangles in the grid is $M + N = \binom{n}{2}^2$. Therefore, we have
\[
E \ge M + 2N = \binom{n}{2}^2 + N \iff N \le E - \binom{n}{2}^2.
\]

To bound $N$, we provide an upper bound on $E$. For each cell $c$, define:
- $f(c)$ to be the number of cells in the same row as $c$ which contain a smaller integer than $c$,
- $g(c)$ to be the number of cells in the same column as $c$ which contain a smaller integer than $c$.

The number of elbows centered at $c$ is exactly $f(c)g(c)$. Thus, the total number of elbows satisfies
\[
E = \sum_c f(c)g(c) \le \sum_c \frac{1}{2}\bigl[f(c)^2+g(c)^2\bigr].
\]
In any given row, the values of $f(c)$ for the $n$ cells are exactly a permutation of $0, 1, \dots, n-1$. Thus, the sum of $f(c)^2$ over all cells in the grid is $n \sum_{k=0}^{n-1} k^2$. The same holds for $g(c)^2$ over all columns. Therefore,
\[
\sum_c \frac{1}{2}\bigl[f(c)^2+g(c)^2\bigr] = n\bigl(0^2+1^2+\dots+(n-1)^2\bigr) = \frac{n^2(n-1)(2n-1)}{6}.
\]
It follows that the number of wobbly rectangles satisfies
\begin{align*}
N &\le E - \binom{n}{2}^2 \\
&\le \frac{n^2(n-1)(2n-1)}{6} - \frac{n^2(n-1)^2}{4} \\
&= \frac{n^2(n-1) [2(2n-1) - 3(n-1)]}{12} \\
&= \frac{n^2(n-1)(n+1)}{12} \\
&= \frac{n^2(n^2-1)}{12}
\end{align*}
as desired.

**Construction:**
From the proof above, equality holds if and only if $f(c)=g(c)$ everywhere.

Select any $n\times n$ Latin square on the symbols $0, 1, \dots, n-1$. Replace the $n$ copies of symbol $k$ with the integers $kn+1, kn+2, \dots, kn+n$ in any order. This construction is valid because, for each cell $c$, all cells in its row and column that contain a smaller integer are exactly those cells that received a strictly smaller symbol in the Latin square. Since each symbol appears exactly once in each row and column, the number of strictly smaller symbols in $c$'s row is exactly the symbol originally placed in $c$. Thus, $f(c)$ equals the original symbol in $c$. By the same reasoning, $g(c)$ also equals the original symbol in $c$. Therefore, $f(c) = g(c)$ everywhere, which achieves the maximum possible number of wobbly rectangles $N = \frac{n^2(n^2-1)}{12}$.

Grading guidelines:
(Partial) 1. Observed (and justified) that in any axis-aligned rectangle, the vertex containing the largest of the four entries is the center of an “elbow” (i.e. larger than its two adjacent vertices in the rectangle), hence every rectangle contains at least one elbow. 2. Introduced the elbow count E and derived a correct inequality relating N to E and the total number of rectangles, e.g. by showing wobbly rectangles contribute exactly 2 elbows while non-wobbly contribute at least 1, leading to N <= E - C(n,2)^2 (or an equivalent bound). 3. For a cell c defined f(c), g(c) as the numbers of smaller entries in its row/column, and correctly showed that the number of elbows centered at c equals f(c)g(c), hence E = sum_c f(c)g(c). (Almost) 1. Completed the upper-bound proof (including the estimate E <= n(0^2+1^2+...+(n-1)^2) and concluding N <= n^2(n^2-1)/12) but did not provide a construction achieving equality, or only sketched it without verifying the needed equalities. 2. Gave the intended extremal construction (e.g. via a Latin square ensuring f(c)=g(c) for all cells) and explained why it should be optimal, but left a localized gap such as not fully proving that equality in the AM-GM/Cauchy step forces f(c)=g(c) everywhere, or not fully checking that the construction indeed makes f(c)=g(c) for every cell. 3. Solution obtains the correct final formula and has the main counting/optimization framework, but contains a minor algebraic slip (e.g. in simplifying to n^2(n^2-1)/12) or an unchecked boundary case; the rest of the argument is correct.

Construction task:
For the specific case $n=20$, provide an explicit construction of the $20 \times 20$ table that maximizes $N$.

Construction requirements:
- Output a single Python expression (a list of lists of integers) representing the $20 \times 20$ table.
- The table must contain every integer from 1 to 400 exactly once.
- The configuration must maximize $N$, the number of axis-aligned rectangles where the two smallest integers among the rectangle's four vertices are located on diagonally opposite vertices.
- The construction must be a single, standalone Python expression that can be directly evaluated using `eval()`.
- Do not include explanations, comments, markdown code blocks, print statements, assignments, function definitions, imports, classes, asserts, or block `for` statements.
- Prefer using list comprehensions, conditional expressions, and integer constants to generate a regular, compact, and reproducible expression.
- Put ONLY the Python expression inside the `<construct>...</construct>` tags.

Reference construction:
[[((j - i) % 20) * 20 + i + 1 for j in range(20)] for i in range(20)]

Verifier code:
import sys

def verify():
    payload = sys.stdin.read().strip()
    if not payload:
        print("Error: Empty input.")
        return

    try:
        # Evaluate the payload as a Python expression (supports list comprehensions)
        table = eval(payload)
    except Exception as e:
        print(f"Parse error: {e}")
        return

    # Check that the parsed object is a list of exactly 20 lists
    if not isinstance(table, list):
        print("Error: The evaluated payload is not a list.")
        return
    
    if len(table) != 20:
        print(f"Error: Expected exactly 20 rows, got {len(table)}.")
        return
    
    for i, row in enumerate(table):
        if not isinstance(row, list):
            print(f"Error: Row {i} is not a list.")
            return
        if len(row) != 20:
            print(f"Error: Row {i} does not have exactly 20 elements (has {len(row)}).")
            return
        for j, val in enumerate(row):
            if type(val) is not int:
                print(f"Error: Element at row {i}, col {j} is not an integer.")
                return

    # Flatten the matrix and verify it contains all integers from 1 to 400 exactly once
    flattened = [val for row in table for val in row]
    expected_elements = list(range(1, 401))
    if sorted(flattened) != expected_elements:
        print("Error: The table does not contain every integer from 1 to 400 exactly once.")
        return

    # Initialize counter N
    N = 0
    
    # Iterate over all pairs of rows r1 < r2 and all pairs of columns c1 < c2
    for r1 in range(20):
        for r2 in range(r1 + 1, 20):
            for c1 in range(20):
                for c2 in range(c1 + 1, 20):
                    # Extract the four corner values
                    v1 = table[r1][c1]
                    v2 = table[r1][c2]
                    v3 = table[r2][c1]
                    v4 = table[r2][c2]
                    
                    corners = [
                        (v1, r1, c1),
                        (v2, r1, c2),
                        (v3, r2, c1),
                        (v4, r2, c2)
                    ]
                    
                    # Sort the four values to find the two smallest integers
                    corners.sort(key=lambda x: x[0])
                    
                    s1 = corners[0]
                    s2 = corners[1]
                    
                    # Check if the two smallest integers are diagonally opposite
                    # (i.e., they do not share the same row and do not share the same column)
                    if s1[1] != s2[1] and s1[2] != s2[2]:
                        N += 1
                        
    # Assert that N is exactly 13,300
    if N != 13300:
        print(f"Error: The number of valid rectangles N is {N}, but expected exactly 13300.")
        return
        
    print("True")

if __name__ == "__main__":
    verify()