Source: USAMO-2009-P3
Category: Existence and Construction

Problem: We define a \emph{chessboard polygon} to be a simple polygon whose sides are
situated along lines of the form $x=a$ or $y=b$, where $a$ and $b$ are integers.
These lines divide the interior into unit squares, which are shaded alternately
gray and white so that adjacent squares have different colors.
To tile a chessboard polygon by dominoes is to
exactly cover the polygon by non-overlapping $ 1 \times 2$ rectangles.
Finally, a \emph{tasteful tiling} is one which avoids the
two configurations of dominoes and colors shown on the left below.

Prove that (a) if a chessboard polygon can be tiled by dominoes, then it can be done so tastefully, and (b) such a tasteful tiling is unique.

Answer: Proof.

Reference solution:
\paragraph{Proof of (a).}
This can be proven by induction on the number of dominoes in the tiling. Let $\mathcal{P}$ denote the chessboard polygon which can be tiled by dominoes. Consider a \emph{lower-left} square $s$ of the polygon, and without loss of generality, assume it is white (the other case is similar). Then we have two cases:
\begin{itemize}
    \item If there exists a domino tiling of $\mathcal{P}$ where $s$ is covered by a vertical domino, then delete this domino and apply induction on the rest of $\mathcal{P}$. Adding this domino back will not create any distasteful configurations.
    \item Otherwise, assume $s$ is covered by a horizontal domino in \emph{every} tiling. Again, delete this domino and apply induction on the rest of $\mathcal{P}$. The resulting tasteful tiling of the remaining polygon cannot have another horizontal domino adjacent to the one covering $s$, because otherwise we could have replaced that $2 \times 2$ square with two vertical dominoes to obtain a tiling of $\mathcal{P}$ where $s$ is covered by a vertical domino, arriving at the first case. Thus, adding this horizontal domino back will not create any distasteful configurations.
\end{itemize}

\paragraph{Proof of (b).}
We now turn to proving uniqueness. Suppose for contradiction there are two distinct tasteful tilings. Overlaying the two tilings on top of each other induces several \emph{cycles} of overlapping dominoes at positions where the tilings differ. Henceforth, it will be convenient to work with the lattice $\mathbb{Z}^2$, treating the squares as black and white points. Let $\gamma$ be any such cycle and let $s$ denote a lower-left point of $\gamma$; without loss of generality, assume it is black. Orient $\gamma$ counterclockwise. Restrict attention to the lattice polygon $\mathcal{Q}$ enclosed by $\gamma$ (we consider points of $\gamma$ as part of $\mathcal{Q}$). In one of the two tilings of the lattice points of $\mathcal{Q}$, the point $s$ will be covered by a horizontal domino; in the other tiling $s$ will be covered by a vertical domino. From now on we will focus only on the latter one. Observe that we now have a set of dominoes along $\gamma$, such that $\gamma$ points from the white point to the black point within each domino.

Now impose coordinates so that $s = (0,0)$. Consider the staircase sequence of points $p_0 = s = (0,0)$, $p_1 = (1,0)$, $p_2 = (1,1)$, $p_3 = (2,1)$, and so on. By hypothesis, $p_0$ is covered by a vertical domino. Then $p_1$ must be covered by a horizontal domino to avoid a distasteful configuration. Then if $p_2$ is in $\mathcal{Q}$, it must be covered by a vertical domino to avoid a distasteful configuration, and so on. We may repeat this argument as long as the points $p_i$ lie inside $\mathcal{Q}$. The curve $\gamma$ by definition should cross the line $\ell$ defined by $y = x - 1$ at the point $b = (1,0)$. Let $a$ denote the first point of this sequence after $p_1$ for which $\gamma$ \emph{crosses} $\ell$ again. Now $a$ is tiled by a vertical domino whose black point is to the right of $\ell$. But the line $\ell$ cuts $\mathcal{Q}$ into two parts, and the orientation of $\gamma$ has this path also entering from the right. This contradicts the fact that the orientation of $\gamma$ points only from white to black within dominoes. This contradiction completes the proof.

Grading guidelines:
(Partial) 1. For part (a), used the “lower-left square” idea and correctly split into the two cases: (i) there exists a tiling with the lower-left square covered vertically, (ii) otherwise it is forced horizontal in every tiling. 2. Justified the key local switch: if a horizontal domino adjacent to the forced horizontal domino forms a full 2×2 block, then replacing the two horizontal dominoes by two vertical dominoes produces a tiling with the lower-left square vertical (contradicting the forced-horizontal case). 3. For part (b), observed that overlaying two tilings decomposes the symmetric difference into disjoint alternating cycles of dominoes (each cycle enclosing a region) and reduced uniqueness to ruling out the existence of one such cycle under tastefulness. (Almost) 1. Gave an essentially complete induction proof of (a) producing a tasteful tiling, but did not fully justify why adding back the removed domino cannot create either forbidden configuration in one of the two cases. 2. Proved (b) by the cycle/alternating-loop method and obtained a contradiction using a monotone “staircase” propagation (forced alternation of orientations to avoid forbidden patterns), but left a localized gap in the final topological step (e.g., why the chosen cycle must cross the line y=x−1 as required, or why the crossing/orientation argument forces a contradiction). 3. Solution is almost complete, but made minor mistakes which are not negligible.

Construction task:
For the specific case of a $20 \times 21$ rectangular chessboard polygon (20 rows, 21 columns), provide a tasteful tiling by dominoes.

Construction requirements:
- Output a single Python expression that evaluates to a list of 20 lists, each of length 21, representing the grid.
- Each entry must be a string in the format "W_k" or "B_k", where 'W'/'B' indicates the color of the square (White/Black) and $k$ is a positive integer representing the domino ID.
- The grid coloring must follow the standard chessboard pattern with the top-left square (0,0) being White ("W").
- Each domino ID $k$ must appear exactly twice, and the two cells with that ID must be edge-adjacent, so that each domino covers exactly two adjacent squares, one white and one black.
- The tiling must be "tasteful", meaning it contains none of the following $2 \times 2$ subgrid configurations (where $k \neq t$):
  1. Vertical pair configuration `[[W_k, B_t], [B_k, W_t]]` (two vertical dominoes filling the $2 \times 2$ block when the top-left square is White).
  2. Horizontal pair configuration `[[B_k, W_k], [W_t, B_t]]` (two horizontal dominoes filling the $2 \times 2$ block when the top-left square is Black).
- The output must be a single, valid Python expression. Do not include explanations, comments, assignments, imports, function definitions, markdown formatting, or any non-expression content.
- Put ONLY the Python expression inside the construction block.

Reference construction:
[[('W' if (r+c)%2==0 else 'B')+'_'+str(D[(r,c)]) for c in range(21)] for D in [{cell:k for k,pair in enumerate([((r,c),(r,c+1)) for r,hm in enumerate([349525,174762,87380,43688,21840,10912,5440,2688,1280,512,512,1280,2688,5440,10912,21840,43688,87380,174762,349525]) for c in range(20) if (hm>>c)&1] + [((r,c),(r+1,c)) for r,vm in enumerate([1048576,524289,1310722,655365,1376266,688149,1392682,696405,1396906,698709,1396906,696405,1392682,688149,1376266,655365,1310722,524289,1048576,0]) for c in range(21) if (vm>>c)&1],1) for cell in pair}] for r in range(20)]

Verifier code:
import sys
import ast

def verify():
    try:
        payload = sys.stdin.read().strip()
    except Exception as e:
        print(f"Error reading input: {e}")
        return

    if not payload:
        print("Error: Input is empty.")
        return

    try:
        tree = ast.parse(payload, mode="eval")
        grid = eval(
            compile(tree, "<construction>", "eval"),
            {"__builtins__": {}, "range": range, "enumerate": enumerate, "str": str, "len": len},
            {},
        )
    except Exception as e:
        print(f"Error: Input is not a valid allowed Python expression. {e}")
        return

    rows, cols = 20, 21

    if not isinstance(grid, list):
        print("Error: Input must evaluate to a list.")
        return
    if len(grid) != rows:
        print(f"Error: Grid must have exactly {rows} rows, found {len(grid)}.")
        return

    parsed = [[None for _ in range(cols)] for _ in range(rows)]
    dominoes = {}

    for r, row in enumerate(grid):
        if not isinstance(row, list):
            print(f"Error: Row {r} is not a list.")
            return
        if len(row) != cols:
            print(f"Error: Row {r} must have exactly {cols} columns, found {len(row)}.")
            return
        for c, cell in enumerate(row):
            if not isinstance(cell, str):
                print(f"Error: Cell ({r}, {c}) is not a string.")
                return
            parts = cell.split("_")
            if len(parts) != 2:
                print(f"Error: Cell ({r}, {c}) '{cell}' invalid format. Expected 'Color_ID'.")
                return
            color, id_text = parts
            expected_color = "W" if (r + c) % 2 == 0 else "B"
            if color != expected_color:
                print(f"Error: Cell ({r}, {c}) has color '{color}', expected '{expected_color}'.")
                return
            if not id_text.isdigit():
                print(f"Error: Cell ({r}, {c}) ID '{id_text}' is not a positive integer string.")
                return
            k = int(id_text)
            if k <= 0:
                print(f"Error: Cell ({r}, {c}) ID {k} must be positive.")
                return
            parsed[r][c] = {"color": color, "id": k}
            dominoes.setdefault(k, []).append((r, c))

    expected_ids = set(range(1, rows * cols // 2 + 1))
    actual_ids = set(dominoes)
    if actual_ids != expected_ids:
        missing = sorted(expected_ids - actual_ids)
        extra = sorted(actual_ids - expected_ids)
        if missing:
            print(f"Error: Missing domino IDs, first few: {missing[:10]}.")
            return
        print(f"Error: Unexpected domino IDs, first few: {extra[:10]}.")
        return

    for k in range(1, rows * cols // 2 + 1):
        cells = dominoes[k]
        if len(cells) != 2:
            print(f"Error: Domino ID {k} appears {len(cells)} times. Must appear exactly twice.")
            return
        (r1, c1), (r2, c2) = cells
        dr = abs(r1 - r2)
        dc = abs(c1 - c2)
        if not ((dr == 1 and dc == 0) or (dr == 0 and dc == 1)):
            print(f"Error: Domino {k} cells ({r1},{c1}) and ({r2},{c2}) are not edge-adjacent.")
            return
        if parsed[r1][c1]["color"] == parsed[r2][c2]["color"]:
            print(f"Error: Domino {k} does not cover one white and one black square.")
            return

    for r in range(rows - 1):
        for c in range(cols - 1):
            tl = parsed[r][c]
            tr = parsed[r][c + 1]
            bl = parsed[r + 1][c]
            br = parsed[r + 1][c + 1]

            if tl["color"] == "W":
                if tl["id"] == bl["id"] and tr["id"] == br["id"] and tl["id"] != tr["id"]:
                    print(f"Error: Forbidden vertical pair at 2x2 block with top-left ({r}, {c}).")
                    return
            else:
                if tl["id"] == tr["id"] and bl["id"] == br["id"] and tl["id"] != bl["id"]:
                    print(f"Error: Forbidden horizontal pair at 2x2 block with top-left ({r}, {c}).")
                    return

    print("True")

if __name__ == "__main__":
    verify()