Source: IMO-2022-P6
Category: Extremal Problems

Problem: Let $n$ be a positive integer. A Nordic square is an $n \\times n$ board containing all the integers from $1$ to $n^2$ so that each cell contains exactly one number. An uphill pathis a sequence of one or more cells such that:\n1. the first cell in the sequence is a valley, meaning the number written is less than all its orthogonal neighbors,\n2. each subsequent cell in the sequence is orthogonally adjacent to the previous cell, and\n3. the numbers written in the cells in the sequence are in increasing order. \nFind, as a function of n, the smallest possible total number of uphill paths in a Nordic square.

Answer: $2n^2-2n+1$

Reference solution:
Answer: $2n^2-2n+1$

\paragraph{Bound.}
The lower bound is established as follows:
\begin{itemize}
    \item For any pair of orthogonally adjacent cells, say $a > b$, one can extend the step $a \to b$ to a downhill path (the reverse of an uphill path) by repeatedly moving to a smaller adjacent cell until a valley is reached. Reversing this sequence gives a distinct uphill path of length $\ge 2$ ending with the step $b \to a$. Since there are $2n(n-1)$ pairs of adjacent cells in the grid, this gives at least $2n(n-1)=2n^2-2n$ uphill paths of length $\ge 2$.
    \item There is always at least one uphill path of length $1$, namely the single cell containing $1$ (or indeed any valley).
\end{itemize}
Summing these yields at least $2n^2-2n+1$ uphill paths.

\paragraph{Construction.}
For the construction, the idea is to build a tree $T$ on the grid such that no two cells not in $T$ are adjacent. (Such a tree can be explicitly constructed for any $n$; for example, one can design a periodic pattern that forms a tree for grids where $3 \mid n$, and then adapt it to any $n$ by cropping the last $n \bmod 3$ rows and the necessary columns, ensuring that the cells not in $T$ remain strictly isolated from one another.) 

Place $1$ anywhere in $T$, and then place all the small numbers up to $|T|$ inside $T$ such that the numbers strictly increase along the unique paths in $T$ branching out from $1$. Then, place the remaining numbers outside $T$ arbitrarily. 

Because no two cells outside $T$ are adjacent, every neighbor of a cell outside $T$ belongs to $T$. Since all numbers in $T$ are at most $|T|$ and all numbers outside $T$ are strictly greater than $|T|$, any cell outside $T$ contains a strictly greater number than all its neighbors. Consequently, no cell outside $T$ can be a valley, making $1$ the unique valley in the entire grid. 

By construction, any uphill path must start from $1$. Furthermore, because $T$ is a tree and the numbers increase along its branches, the sequence of cells from $1$ to any cell $b \in T$ is unique. Thus, an uphill path is uniquely determined by its final step $b \to a$ (where $b \in T$, and $a$ is either in $T$ or outside $T$). This implies that the only uphill paths are exactly the length-$1$ path at $\{1\}$ and the reverses of the uniquely determined downhill paths we counted in the lower bound. This achieves exactly $2n^2-2n+1$ uphill paths.

Grading guidelines:
(Partial) 1. Established the lower bound idea: for each adjacent pair of cells with values a>b, following a strictly decreasing walk to a valley and reversing it yields an uphill path of length ≥2 ending with the step b→a. 2. Correctly counted the number of orthogonally adjacent pairs in an n×n grid as 2n(n−1), and concluded there are at least 2n^2−2n uphill paths of length ≥2. 3. Noted that at least one uphill path of length 1 always exists (e.g. the single cell containing 1, or any valley), and combined with the previous bound to get ≥2n^2−2n+1. (Almost) 1. Gave the full lower bound 2n^2−2n+1 and a construction intended to match it using a set/tree T so that no two cells outside T are adjacent, but did not fully justify the existence of such a T for all n (or left a gap in the “cropping/adaptation” argument). 2. Provided the construction and argued (correctly in outline) that 1 is the unique valley and every uphill path starts at 1, but did not rigorously justify that each adjacent step corresponds to a unique uphill path (e.g. the uniqueness of the increasing path inside T, or why no extra uphill paths arise). 3. Solution is almost complete, but made minor mistakes which are not negligible.

Construction task:
For the specific case $n=64$, provide an explicit construction of the $64 \times 64$ Nordic square that minimizes the total number of uphill paths.

Construction requirements:
- Output a single Python expression that evaluates to a list of 64 lists, representing the $64 \times 64$ grid.
- Each inner list should correspond to a row in the grid, containing 64 integers.
- The grid must contain all integers from 1 to $64^2$ exactly once.
- The configuration must minimize the total number of uphill paths.
- The output must be a single, valid Python expression (e.g., using list comprehensions). Do not include any assignments, imports, function definitions, or extra text.
- Put ONLY the Python expression inside the construction block.

Reference construction:
[
    [val_dict[(R, C)] for C in range(64)]
    for dist_dict in [{
        (r, c): (
            8*(r//6) + (0 if c==1 else c-1) if r%6==0 and c>=1 else
            8*(r//6) + 1 if r%6==1 and c==1 else
            8*(r//6) + 2 if r%6==1 and c==0 else
            8*(r//6) + c if r%6==1 and c>=3 and c%2==1 else
            8*(r//6) + 3 if r%6==2 and c==0 else
            8*(r//6) + c + 5 if r%6==2 and c>=2 and c%2==0 else
            8*(r//6) + 4 if r%6==3 and c==0 else
            8*(r//6) + c + 4 if r%6==3 and c>=1 else
            8*(r//6) + 5 if r%6==4 and c==0 else
            8*(r//6) + c + 5 if r%6==4 and c>=2 and c%2==0 else
            8*(r//6) + 6 if r%6==5 and c==0 else
            8*(r//6) + 7 if r%6==5 and c==1 else
            8*(r//6+1) + c if r%6==5 and c>=3 and c%2==1 else
            -1
        ) for r in range(64) for c in range(64)
    }]
    for val_dict in [{
        p: i+1 for i, p in enumerate(
            [p for d, p in sorted([(d, p) for p, d in dist_dict.items() if d != -1])] +
            [p for d, p in sorted([(d, p) for p, d in dist_dict.items() if d == -1])]
        )
    }]
    for R in range(64)
]

Verifier code:
import sys

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

    # 1. Evaluate the raw string payload using eval() to obtain the Python object.
    try:
        grid = eval(input_text)
    except Exception as e:
        print(f"Error parsing input: {e}")
        return

    # 2. Verify that the parsed object is a list of exactly 64 elements, 
    # and each element is a list of exactly 64 integers.
    if type(grid) is not list:
        print("Error: The parsed object is not a list.")
        return
    if len(grid) != 64:
        print(f"Error: Expected 64 rows, got {len(grid)}.")
        return
    for i, row in enumerate(grid):
        if type(row) is not list:
            print(f"Error: Row {i} is not a list.")
            return
        if len(row) != 64:
            print(f"Error: Row {i} does not have exactly 64 elements.")
            return
        for j, val in enumerate(row):
            if type(val) is not int:
                print(f"Error: Element at ({i}, {j}) is not an integer.")
                return

    # 3. Flatten the grid and verify that it contains all integers from 1 to 4096 exactly once.
    flattened = [val for row in grid for val in row]
    if len(flattened) != 4096:
        print("Error: Total number of elements is not 4096.")
        return
    
    counts = set(flattened)
    if len(counts) != 4096:
        print("Error: Elements in the grid are not distinct.")
        return
    
    min_val, max_val = min(counts), max(counts)
    if min_val != 1 or max_val != 4096:
        print(f"Error: Grid values must be from 1 to 4096. Found min {min_val}, max {max_val}.")
        return

    def get_neighbors(r, c):
        for nr, nc in ((r-1, c), (r+1, c), (r, c-1), (r, c+1)):
            if 0 <= nr < 64 and 0 <= nc < 64:
                yield nr, nc

    # 4. Iterate over all cells in the grid to identify all "valleys".
    valleys = []
    for r in range(64):
        for c in range(64):
            is_valley = True
            for nr, nc in get_neighbors(r, c):
                if grid[nr][nc] <= grid[r][c]:
                    is_valley = False
                    break
            if is_valley:
                valleys.append((r, c))

    # 5. Traverse and count all valid "uphill paths" originating from each valley.
    # We use a Dynamic Programming approach processing cells in descending order 
    # to efficiently count paths and avoid recursion limits.
    cells = []
    for r in range(64):
        for c in range(64):
            cells.append((grid[r][c], r, c))
    cells.sort(reverse=True)
    
    paths_from = [[1] * 64 for _ in range(64)]
    for val, r, c in cells:
        for nr, nc in get_neighbors(r, c):
            if grid[nr][nc] > grid[r][c]:
                paths_from[r][c] += paths_from[nr][nc]
                
    # 6. Sum the total number of uphill paths across all valleys.
    total_uphill_paths = 0
    for vr, vc in valleys:
        total_uphill_paths += paths_from[vr][vc]

    # 7. Verify that the total number of uphill paths is exactly 8065.
    if total_uphill_paths != 8065:
        print(f"Error: Expected exactly 8065 uphill paths, but found {total_uphill_paths}.")
        return

    print("True")

if __name__ == "__main__":
    verify()