Datasets:
| {"split": "construction", "source": "IMO-2025-P6", "category": "Extremal Problems", "id": "IMO-2025-P6-23", "query": "Consider a $2025 \\\\times 2025$ grid of unit squares. Matilda wishes to place on the grid some rectangular tiles, possibly of different sizes, such that each side of every tile lies on a grid line and every unit square is covered by at most one tile. Determine the minimum number of tiles Matilda needs to place so that each row and each column of the grid has exactly one unit square that is not covered by any tile.", "ref_answer": "2112", "instruction": "For the specific case where the grid size is $529 \\times 529$ (corresponding to $G=23$), provide an explicit construction of the tiles.\n\nConstruction requirements:\n- Place the minimum possible number of rectangles such that each row and each column of the grid has exactly one unit square not covered by any tile.\n- Output a single Python expression that evaluates to a list of rectangles.\n- Each rectangle must be represented as a list of four integers `[r1, r2, c1, c2]`, covering all cells `(r, c)` such that `r1 <= r <= r2` and `c1 <= c <= c2`.\n- Use 0-based indexing for coordinates, so rows and columns range from 0 to 528.\n- The rectangles must not overlap, and the union of all rectangles must leave exactly one cell uncovered in each of the 529 rows and 529 columns.\n- The output must be a single, valid Python expression (e.g., using list comprehensions and list concatenation) that can be directly evaluated by `eval()`.\n- Do NOT include any explanations, comments, markdown formatting (like ```python), assignments, imports, or any non-expression content.\n- Put ONLY the raw Python expression inside the construction block.", "ref_construction": "[[23 * i + j + 1, 23 * i + j + 23, 23 * j - i + 22, 23 * j - i + 44] for i in range(22) for j in range(22)] + [[0, j, 23 * j + 23, 23 * j + 45] for j in range(22)] + [[23 * i, 23 * i + 22, 0, 21 - i] for i in range(22)] + [[507 + j, 528, 23 * j, 23 * j + 22] for j in range(22)] + [[23 * i + 23, 23 * i + 45, 528 - i, 528] for i in range(22)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty payload\")\n return\n\n try:\n # The instruction explicitly requires a Python expression that can be evaluated by eval(),\n # such as list comprehensions and list concatenations.\n rects = eval(payload)\n except Exception as e:\n print(f\"Failed to parse payload: {e}\")\n return\n\n if not isinstance(rects, list):\n print(\"Parsed object is not a list\")\n return\n\n if len(rects) != 572:\n print(f\"Expected exactly 572 rectangles, got {len(rects)}\")\n return\n\n grid = [[False] * 529 for _ in range(529)]\n\n for idx, rect in enumerate(rects):\n if not (isinstance(rect, (list, tuple)) and len(rect) == 4):\n print(f\"Rectangle at index {idx} is not a list or tuple of 4 elements\")\n return\n \n r1, r2, c1, c2 = rect\n if not (type(r1) is int and type(r2) is int and type(c1) is int and type(c2) is int):\n print(f\"Rectangle at index {idx} contains non-integer coordinates\")\n return\n \n if not (0 <= r1 <= r2 < 529 and 0 <= c1 <= c2 < 529):\n print(f\"Rectangle at index {idx} has out-of-bounds or invalid coordinates: {rect}\")\n return\n \n for r in range(r1, r2 + 1):\n for c in range(c1, c2 + 1):\n if grid[r][c]:\n print(f\"Rectangles overlap at cell ({r}, {c})\")\n return\n grid[r][c] = True\n\n for r in range(529):\n uncovered_count = grid[r].count(False)\n if uncovered_count != 1:\n print(f\"Row {r} has {uncovered_count} uncovered cells, expected exactly 1\")\n return\n\n for c in range(529):\n uncovered_count = sum(not grid[r][c] for r in range(529))\n if uncovered_count != 1:\n print(f\"Column {c} has {uncovered_count} uncovered cells, expected exactly 1\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()", "grading_guidelines": "(Partial) 1. Gave a valid construction using 32 tiles (or the general pattern for n=k^2) and correctly verified that it leaves exactly one uncovered square in each row and each column. 2. Observed that the uncovered squares form a permutation of {1,…,25} (one per row and per column), and introduced an LIS of length a and an LDS of length b with the correct inequality ab≥25 (or max(a,b)≥5). 3. Set up a meaningful lower-bound framework by marking letters N/E/S/W adjacent to uncovered squares using the LIS/LDS partition, and stated (with some justification) that no tile can contain two marked letters. (Almost) 1. Proved the lower bound ≥32 via the LIS/LDS letter-counting method, but made a localized counting slip (e.g. miscounted by 1 the total number of letters C, or mishandled the case of LIS and LDS intersecting vs disjoint). 2. Completed the construction and essentially all of the lower-bound proof, but did not fully justify Claim 2 (that no tile can contain more than one letter) in one of the four regions or along the LIS/LDS boundary. 3. Gave the full LIS/LDS framework and derived ≥ n+2√n−3 for n=25, but omitted the off-board-letter correction (subtracting at most 4) or the extra-tile correction in the disjoint case, leaving the final bound at 31 or 33 without resolving the discrepancy.", "ref_solution": "The answer is $32 = 25 + 2(5) - 3$.\n\nIn general, for an $n \\times n$ grid, the answer turns out to be $\\left\\lceil n + 2 \\sqrt n - 3 \\right\\rceil$, but when $n$ is not a perfect square the solution is more complicated. Here $n=25$.\n\n**Construction.**\nWe describe a general construction when $n = k^2$ (for this problem, $k=5$); it generalizes readily. There are a total of $(k-1)^2$ tiles which are $k \\times k$ squares and another $4(k-1)$ tiles on the boundary, giving a total of\n\\[ (k-1)^2 + 4(k-1) = k^2 + 2k - 3 \\]\ntiles as promised. For $k=5$, this yields $16 + 16 = 32$ tiles.\n\n**Bound.**\nThere are several approaches, but the shortest proof seems to be the following one that exploits the Erdős–Szekeres theorem. The theorem being quoted is:\n\n**Theorem (Erdős–Szekeres).**\n*Let $n \\ge 1$ be an integer. Given a permutation of $(1, \\dots, n)$, if a longest increasing subsequence (LIS) has length $a$ and a longest decreasing subsequence (LDS) has length $b$, then $ab \\ge n$.*\n\nThis is a stronger version of the theorem compared to another version which instead just asserts that $\\max(a,b) \\ge \\sqrt n$.\n\nTo apply this to the present problem, take the $n$ uncovered squares, which we henceforth call \"black\", as a permutation. Then consider both an LIS of length $a$ and an LDS of length $b$. We do the following illustration:\n- Draw the LIS as a broken line, then connect it to the southwest and northeast corners of the board.\n- Similarly, draw the LDS as a broken line, then connect it to the northwest and southeast corners of the board.\n- These two steps partition the board into four quadrants, which we call north, east, south, and west.\n- For each black cell in the north quadrant, write an $\\mathbf{N}$ in the cell above it (for a cell in the first row, this will be off the board). Do the same for $\\mathbf{E}$ (east, in the cell to the right), $\\mathbf{S}$ (south, in the cell below), and $\\mathbf{W}$ (west, in the cell to the left).\n- Some black cells are in multiple quadrants (i.e., part of the LIS/LDS). Write all corresponding letters in that case.\n\nWe observe that:\n\n**Claim 1.**\nIn this algorithm, the total number of letters written is exactly\n\\[\n C \\coloneq \\begin{cases}\n n + a + b + 1 & \\text{if the LIS and LDS intersect} \\\\\n n + a + b & \\text{otherwise}.\n \\end{cases}\n\\]\n\n*Proof.*\nThis is obvious. Each black square contributes at least one letter. Each black square on exactly one of the LIS and LDS contributes one extra letter. And a black square on both contributes $4$ letters instead of $1+1+1$.\n\nNote by AM–GM we have $a + b \\ge 2 \\sqrt{ab} \\ge 2 \\sqrt n$, so we have a bound of\n\\[ C \\ge n + 2 \\sqrt n + \\varepsilon \\quad\\text{where}\\quad\n \\varepsilon \\coloneq \\begin{cases}\n 1 & \\text{if the LIS and LDS intersect} \\\\\n 0 & \\text{otherwise}.\n \\end{cases} \\]\n\nTo relate $C$ to the number of tiles, the critical claim is the following, which is by construction:\n\n**Claim 2.**\nNone of Matilda's tiles can have more than one letter written on it.\n\n*Proof.*\nThis follows from the construction.\n\nWe split into two cases based on $\\varepsilon$:\n- When $\\varepsilon = 1$, at most four letters go off the grid (one for each direction), so the number of tiles is at least $C - 4 \\ge n + 2 \\sqrt n - 3$.\n- Suppose $\\varepsilon = 0$. Then $C - 4 \\ge n + 2 \\sqrt n - 4$. However, we make the additional observation here that the tile where the LIS and LDS meet has no letters on it either; hence there are at least $1 + (C-4) \\ge n + 2 \\sqrt n - 3$ tiles.\n\nFor $n=25$, this yields a minimum of $25 + 2(5) - 3 = 32$ tiles."} | |
| {"split": "construction", "source": "IMO-2023-P5", "category": "Extremal Problems", "id": "IMO-2023-P5-8", "query": "Let $n$ be a positive integer. A Japanese triangle consists of $1 + 2 + \\cdots + n$ circles arranged in an equilateral triangular shape such that for each $1 \\leq i \\leq n$, the ithrow contains exactly $i$ circles, exactly one of which is colored red. A ninja path in a Japanese triangle is a sequence of $n$ circles obtained by starting in the top row, then repeatedly going from a circle to one of the two circles immediately below it and finishing in the bottom row. In terms of $n$, find the greatest $k$ such that in each Japanese triangle there is a ninja \npath containing at least $k$ red circles.", "ref_answer": "$k = \\lfloor \\log_2(n) \\rfloor + 1$", "ref_solution": "The answer is\n\\[\nk = \\lfloor \\log_2(n) \\rfloor + 1.\n\\]\n\n**Construction (Upper Bound):**\nIt suffices to construct a Japanese triangle for any $n$ such that no ninja path contains more than $\\lfloor \\log_2(n) \\rfloor + 1$ red circles. \nLet the circles be indexed by $(i, j)$, where $i$ is the row number ($1 \\le i \\le n$) and $j$ is the column number ($1 \\le j \\le i$). A ninja path moves from $(i, j)$ to either $(i+1, j)$ or $(i+1, j+1)$ at each step.\nPartition the rows $1, 2, \\dots, n$ into $e = \\lfloor \\log_2(n) \\rfloor + 1$ blocks. For $1 \\le m \\le e$, the $m$-th block consists of rows $i$ such that $2^{m-1} \\le i \\le \\min(n, 2^m - 1)$. \nFor each row $i$ in the $m$-th block, we can write $i = 2^{m-1} + d$ for some integer $0 \\le d < 2^{m-1}$. We place the red circle in row $i$ at column $2d + 1$. (This is a valid position because $2d + 1 \\ge 1$ and $i - (2d + 1) = 2^{m-1} - d - 1 \\ge 0$, so $2d + 1 \\le i$.)\n\nSuppose a ninja path passes through two red circles in the same block $m$, say at rows $i = 2^{m-1} + d$ and $i' = 2^{m-1} + d'$ with $d < d'$. The red circle at row $i$ is at column $2d+1$. At each step, a ninja path can increase its column index by at most $1$. Thus, moving from row $i$ to row $i'$, the column index can increase by at most $i' - i = d' - d$. Therefore, at row $i'$, the path can reach a column index of at most $(2d+1) + (d' - d) = d + d' + 1$. However, the red circle at row $i'$ is located at column $2d' + 1$. Since $d < d'$, we have $d + d' + 1 < 2d' + 1$, meaning the ninja path cannot reach the red circle at row $i'$.\nThis proves that any ninja path contains at most one red circle per block. Since there are $e$ blocks, any ninja path contains at most $e = \\lfloor \\log_2(n) \\rfloor + 1$ red circles.\n\n**Lower Bound (First Proof):**\nConversely, we show that in any Japanese triangle, one can find a ninja path containing at least $\\lfloor \\log_2(n) \\rfloor + 1$ red circles. Let $(i, r_i)$ denote the unique red circle in row $i$.\n\nWe construct a directed graph $T_1$ on the set of all circles by defining the outgoing edges from row $i$ to row $i+1$ (for $1 \\le i < n$) as follows:\n- The red circle $(i, r_i)$ has two outgoing edges, connecting to both circles immediately below it: $(i+1, r_i)$ and $(i+1, r_i+1)$.\n- Any white circle $(i, j)$ to the left of the red circle ($j < r_i$) has one outgoing edge, connecting to $(i+1, j)$.\n- Any white circle $(i, j)$ to the right of the red circle ($j > r_i$) has one outgoing edge, connecting to $(i+1, j+1)$.\n\nIn row $i+1$, circles $(i+1, 1)$ through $(i+1, r_i-1)$ each receive exactly one incoming edge (from the white circles to the left of $r_i$). Circles $(i+1, r_i)$ and $(i+1, r_i+1)$ each receive exactly one incoming edge (from the red circle). Circles $(i+1, r_i+2)$ through $(i+1, i+1)$ each receive exactly one incoming edge (from the white circles to the right of $r_i$). Thus, every circle in row $i+1$ has exactly one incoming edge from row $i$. Since row 1 contains only the root circle $(1,1)$ (which must be red), $T_1$ is a rooted binary tree where every path from the root to a leaf in the bottom row is a valid ninja path.\n\nNext, we build a new rooted tree $T_2$ consisting only of the $n$ red circles. We define the edges of $T_2$ by connecting each red circle to its closest red descendant(s) in $T_1$. That is, a red circle $v$ is a child of a red circle $u$ in $T_2$ if there is a directed path in $T_1$ from $u$ to $v$ containing only white circles as intermediate nodes.\nIn $T_1$, each red circle has exactly two children, and each white circle has exactly one child. Therefore, any path in $T_1$ starting from a child of a red circle $u$ does not branch until it reaches another red circle (or a leaf). This implies that $u$ can have at most two children in $T_2$.\nThus, $T_2$ is a binary tree with $n$ nodes. Let $k$ be the maximum number of nodes on a path from the root to a leaf in $T_2$. Since a binary tree of depth $k$ has at most $2^k - 1$ nodes, we must have $2^k - 1 \\ge n$, which implies $k \\ge \\lfloor \\log_2(n) \\rfloor + 1$.\nThis path of length $k$ in $T_2$ corresponds to a sequence of $k$ red circles that lie on a single path in $T_1$. Since any path in $T_1$ is a valid ninja path, there exists a ninja path containing at least $\\lfloor \\log_2(n) \\rfloor + 1$ red circles.\n\n**Lower Bound (Alternative Recursive Proof):**\nDefine $f(i, j)$ as the maximum number of red circles contained in the portion of a ninja path from $(1, 1)$ down to $(i, j)$, including the endpoints. If $j < 1$ or $j > i$, we define $f(i, j) = 0$. Since every ninja path reaching $(i, j)$ must pass through either $(i-1, j-1)$ or $(i-1, j)$, we have the recurrence:\n\\[\nf(i, j) = \\max \\{f(i-1, j-1), f(i-1, j)\\} + \\begin{cases} 1 & \\text{if } (i, j) \\text{ is red} \\\\ 0 & \\text{otherwise} \\end{cases}\n\\]\nDefine $S_i = \\sum_{j=1}^i f(i, j)$.\n\n**Claim 1:** $S_{i+1} \\ge S_i + \\left\\lceil \\frac{S_i}{i} \\right\\rceil + 1$.\n*Proof.* We evaluate $S_{i+1}$:\n\\[\nS_{i+1} = \\sum_{j=1}^{i+1} \\max \\{f(i, j-1), f(i, j)\\} + \\sum_{j=1}^{i+1} \\begin{cases} 1 & \\text{if } (i+1, j) \\text{ is red} \\\\ 0 & \\text{otherwise} \\end{cases}\n\\]\nSince exactly one circle in row $i+1$ is red, the second sum is exactly $1$. Let $f(i, m)$ be the maximum element among $\\{f(i, 1), \\dots, f(i, i)\\}$. We split the first sum at $m$:\n\\begin{align*}\nS_{i+1} &= \\sum_{j=1}^m \\max \\{f(i, j-1), f(i, j)\\} + \\sum_{j=m+1}^{i+1} \\max \\{f(i, j-1), f(i, j)\\} + 1 \\\\\n&\\ge \\sum_{j=1}^m f(i, j) + \\sum_{j=m+1}^{i+1} f(i, j-1) + 1 \\\\\n&= \\sum_{j=1}^m f(i, j) + \\sum_{j=m}^i f(i, j) + 1 \\\\\n&= S_i + f(i, m) + 1\n\\end{align*}\nSince $f(i, m)$ is the maximum of $i$ integers whose sum is $S_i$, by the Pigeonhole Principle, $f(i, m) \\ge \\lceil \\frac{S_i}{i} \\rceil$. Thus, $S_{i+1} \\ge S_i + \\lceil \\frac{S_i}{i} \\rceil + 1$. $\\blacksquare$\n\n**Claim 2:** Write $n = 2^c + r$, where $0 \\le r < 2^c$. Then $S_n \\ge cn + 2r + 1$.\n*Proof.* We proceed by induction on $n$.\nBase case $n=1$: We have $1 = 2^0 + 0$, so $c=0$ and $r=0$. The only circle in row $1$ is red, so $S_1 = f(1, 1) = 1$. The formula gives $0 \\cdot 1 + 2(0) + 1 = 1$, so the claim holds for $n=1$.\nAssuming the claim holds for some $n=j$, let $j = 2^c + r$. We have:\n\\begin{align*}\nS_{j+1} &\\ge S_j + \\left\\lceil \\frac{S_j}{j} \\right\\rceil + 1 \\\\\n&\\ge cj + 2r + 1 + \\left\\lceil \\frac{cj + 2r + 1}{j} \\right\\rceil + 1 \\\\\n&= cj + 2r + 1 + c + \\left\\lceil \\frac{2r + 1}{j} \\right\\rceil + 1\n\\end{align*}\nSince $j = 2^c + r$ and $r \\le 2^c - 1$, we have $j - (2r+1) = 2^c - r - 1 \\ge 0$, which means $2r+1 \\le j$. Thus, $0 < \\frac{2r+1}{j} \\le 1$, which implies $\\lceil \\frac{2r+1}{j} \\rceil = 1$. Therefore:\n\\[\nS_{j+1} \\ge cj + 2r + 1 + c + 1 + 1 = c(j+1) + 2(r+1) + 1\n\\]\nIf $j+1$ is not a power of $2$, then $j+1 = 2^c + (r+1)$ with $r+1 < 2^c$. The formula matches exactly.\nIf $j+1$ is a power of $2$, then $r+1 = 2^c$, so $j+1 = 2^{c+1}$. We can rewrite the bound as:\n\\[\nc(j+1) + 2(2^c) + 1 = c(j+1) + (j+1) + 1 = (c+1)(j+1) + 2(0) + 1\n\\]\nThis matches the formula for $j+1$ with parameters $c+1$ and $0$. The induction is complete. $\\blacksquare$\n\nFinally, we show that this implies the existence of a path with at least $c+1$ red circles. The average value of $f(n, j)$ for $1 \\le j \\le n$ is $\\frac{S_n}{n}$. Thus, the maximum value is at least $\\lceil \\frac{S_n}{n} \\rceil$. Using Claim 2:\n\\[\n\\left\\lceil \\frac{S_n}{n} \\right\\rceil \\ge \\left\\lceil \\frac{cn + 2r + 1}{n} \\right\\rceil = c + \\left\\lceil \\frac{2r + 1}{n} \\right\\rceil = c + 1\n\\]\nTherefore, there exists some $j$ such that $f(n, j) \\ge c+1$. Since $c = \\lfloor \\log_2(n) \\rfloor$, there is a ninja path containing at least $\\lfloor \\log_2(n) \\rfloor + 1$ red circles.", "grading_guidelines": "(Partial) 1. Gave the correct candidate value k = ⌊log2(n)⌋ + 1, with some justification from small cases or a heuristic (e.g. “at most one per power-of-2 block” or “binary tree depth”). 2. Proved a nontrivial upper bound by an explicit coloring construction showing that some Japanese triangle forces every ninja path to have O(log n) red circles (e.g. partitioning rows into blocks [2^{m-1},2^m−1] and arguing a path cannot hit two reds within one block). 3. Proved a nontrivial lower bound of the form k ≥ ⌊log2(n)⌋ (or k ≥ c+1 where 2^c ≤ n), e.g. by introducing the rooted/binary-tree encoding of paths or a dynamic-programming recurrence f(i,j), but without completing the final counting step. (Almost) 1. Proved the upper bound construction correctly (at most one red per block, hence ≤ ⌊log2(n)⌋+1), and proved the lower bound via the binary-tree argument, but left a minor gap in defining/justifying the tree T2 (e.g. why each red has ≤2 red-children, or why a path in T2 corresponds to a valid ninja path). 2. Proved the lower bound via the f(i,j), S_i method up to a correct inequality such as S_{i+1} ≥ S_i + ⌈S_i/i⌉ + 1 (or an equivalent growth estimate), but made a small induction/boundary slip when converting it into max_j f(n,j) ≥ ⌊log2(n)⌋+1. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For $n=8$, provide an explicit construction of a Japanese triangle that minimizes the maximum number of red circles any ninja path can contain.\n\nRequirements:\n- Represent the triangle as an 8x8 matrix $M$, where $M[i][j]$ is the circle in row $i$, column $j$ (0-indexed).\n- Use `0` for cells outside the triangle (where $j > i$).\n- Use `1` for white circles and `2` for red circles.\n- Each row $i \\in \\{0, \\dots, 7\\}$ must contain exactly one red circle (`2`) among its $i+1$ circles.\n- A ninja path is a sequence of cells $(r, c_r)$ for $r=0, \\dots, 7$ where $c_0=0$ and $c_{r+1} \\in \\{c_r, c_r+1\\}$.\n- Provide exactly one construction block and put ONLY the Python literal list of lists between the tags:\n<construct>\n[...matrix...]\n</construct>\n- Do not use code fences. Do not put any extra text inside <construct>...</construct>.", "ref_construction": "[[2, 0, 0, 0, 0, 0, 0, 0], [2, 1, 0, 0, 0, 0, 0, 0], [1, 1, 2, 0, 0, 0, 0, 0], [2, 1, 1, 1, 0, 0, 0, 0], [1, 1, 2, 1, 1, 0, 0, 0], [1, 1, 1, 1, 2, 1, 0, 0], [1, 1, 1, 1, 1, 1, 2, 0], [2, 1, 1, 1, 1, 1, 1, 1]]", "verify_code": "import sys\nimport ast\n\ndef verify():\n try:\n # Read the entire raw input from stdin\n data = sys.stdin.read().strip()\n if not data:\n print(\"Error: No input provided.\")\n return\n \n # Parse the input using a strict Python-literal strategy\n try:\n matrix = ast.literal_eval(data)\n except Exception as e:\n print(f\"Error: Failed to parse input as a Python literal. {e}\")\n return\n \n # 1. Structural Verification: Matrix must be 8x8\n if not isinstance(matrix, list) or len(matrix) != 8:\n print(f\"Error: Matrix must be a list of 8 rows, but found {len(matrix) if isinstance(matrix, list) else 'non-list'}.\")\n return\n \n for i in range(8):\n if not isinstance(matrix[i], list) or len(matrix[i]) != 8:\n print(f\"Error: Row {i} must be a list of 8 elements.\")\n return\n \n # 2. Constraint Verification: Lower triangular property and red circle constraint\n for i in range(8):\n red_count = 0\n for j in range(8):\n val = matrix[i][j]\n if j > i:\n # Outside the triangle (j > i)\n if val != 0:\n print(f\"Error: Cell ({i}, {j}) is outside the triangle (j > i) and must be 0.\")\n return\n else:\n # Inside the triangle (j <= i)\n if val == 2:\n red_count += 1\n elif val == 1:\n pass\n else:\n print(f\"Error: Cell ({i}, {j}) must be 1 (white) or 2 (red).\")\n return\n \n # Exactly one red circle per row\n if red_count != 1:\n print(f\"Error: Row {i} must contain exactly one red circle (value 2), but found {red_count}.\")\n return\n\n # 3. Mathematical Verification: Dynamic Programming to find the max red circles on any ninja path\n # dp[r][c] stores the maximum number of red circles on a ninja path starting at (0,0) and ending at (r,c)\n dp = [[-1] * 8 for _ in range(8)]\n \n # Initial condition (Row 0)\n # We already verified there is exactly one '2' in row 0, which must be at (0,0)\n dp[0][0] = (1 if matrix[0][0] == 2 else 0)\n \n for r in range(1, 8):\n for c in range(r + 1):\n # A ninja path can reach (r, c) from (r-1, c) or (r-1, c-1)\n prev_max = -1\n \n # Path from (r-1, c)\n if c < r:\n if dp[r-1][c] != -1:\n prev_max = max(prev_max, dp[r-1][c])\n \n # Path from (r-1, c-1)\n if c > 0:\n if dp[r-1][c-1] != -1:\n prev_max = max(prev_max, dp[r-1][c-1])\n \n # If reachable, calculate max red circles for current cell\n if prev_max != -1:\n dp[r][c] = prev_max + (1 if matrix[r][c] == 2 else 0)\n else:\n # Every cell in the triangle should be reachable under ninja path rules\n print(f\"Error: Cell ({r}, {c}) is unreachable, which violates triangle structure.\")\n return\n\n # The objective is the maximum value in the final row\n max_path_reds = max(dp[7])\n \n # The theoretical minimum of the maximum number of red circles for n=8 is floor(log2(8)) + 1 = 4.\n # The instruction asks for a construction that minimizes this maximum.\n if max_path_reds == 4:\n print(\"True\")\n else:\n print(f\"Error: The maximum number of red circles on any ninja path is {max_path_reds}, but it should be 4.\")\n \n except Exception as e:\n print(f\"Error: An unexpected error occurred during verification. {e}\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "IMO-2022-P6", "category": "Extremal Problems", "id": "IMO-2022-P6", "query": "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.", "ref_answer": "$2n^2-2n+1$", "instruction": "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.\n\nConstruction requirements:\n- Output a single Python expression that evaluates to a list of 64 lists, representing the $64 \\times 64$ grid.\n- Each inner list should correspond to a row in the grid, containing 64 integers.\n- The grid must contain all integers from 1 to $64^2$ exactly once.\n- The configuration must minimize the total number of uphill paths.\n- 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.\n- Put ONLY the Python expression inside the construction block.", "ref_construction": "[\n [val_dict[(R, C)] for C in range(64)]\n for dist_dict in [{\n (r, c): (\n 8*(r//6) + (0 if c==1 else c-1) if r%6==0 and c>=1 else\n 8*(r//6) + 1 if r%6==1 and c==1 else\n 8*(r//6) + 2 if r%6==1 and c==0 else\n 8*(r//6) + c if r%6==1 and c>=3 and c%2==1 else\n 8*(r//6) + 3 if r%6==2 and c==0 else\n 8*(r//6) + c + 5 if r%6==2 and c>=2 and c%2==0 else\n 8*(r//6) + 4 if r%6==3 and c==0 else\n 8*(r//6) + c + 4 if r%6==3 and c>=1 else\n 8*(r//6) + 5 if r%6==4 and c==0 else\n 8*(r//6) + c + 5 if r%6==4 and c>=2 and c%2==0 else\n 8*(r//6) + 6 if r%6==5 and c==0 else\n 8*(r//6) + 7 if r%6==5 and c==1 else\n 8*(r//6+1) + c if r%6==5 and c>=3 and c%2==1 else\n -1\n ) for r in range(64) for c in range(64)\n }]\n for val_dict in [{\n p: i+1 for i, p in enumerate(\n [p for d, p in sorted([(d, p) for p, d in dist_dict.items() if d != -1])] +\n [p for d, p in sorted([(d, p) for p, d in dist_dict.items() if d == -1])]\n )\n }]\n for R in range(64)\n]", "verify_code": "import sys\n\ndef verify():\n input_text = sys.stdin.read().strip()\n if not input_text:\n print(\"Error: Empty input.\")\n return\n\n # 1. Evaluate the raw string payload using eval() to obtain the Python object.\n try:\n grid = eval(input_text)\n except Exception as e:\n print(f\"Error parsing input: {e}\")\n return\n\n # 2. Verify that the parsed object is a list of exactly 64 elements, \n # and each element is a list of exactly 64 integers.\n if type(grid) is not list:\n print(\"Error: The parsed object is not a list.\")\n return\n if len(grid) != 64:\n print(f\"Error: Expected 64 rows, got {len(grid)}.\")\n return\n for i, row in enumerate(grid):\n if type(row) is not list:\n print(f\"Error: Row {i} is not a list.\")\n return\n if len(row) != 64:\n print(f\"Error: Row {i} does not have exactly 64 elements.\")\n return\n for j, val in enumerate(row):\n if type(val) is not int:\n print(f\"Error: Element at ({i}, {j}) is not an integer.\")\n return\n\n # 3. Flatten the grid and verify that it contains all integers from 1 to 4096 exactly once.\n flattened = [val for row in grid for val in row]\n if len(flattened) != 4096:\n print(\"Error: Total number of elements is not 4096.\")\n return\n \n counts = set(flattened)\n if len(counts) != 4096:\n print(\"Error: Elements in the grid are not distinct.\")\n return\n \n min_val, max_val = min(counts), max(counts)\n if min_val != 1 or max_val != 4096:\n print(f\"Error: Grid values must be from 1 to 4096. Found min {min_val}, max {max_val}.\")\n return\n\n def get_neighbors(r, c):\n for nr, nc in ((r-1, c), (r+1, c), (r, c-1), (r, c+1)):\n if 0 <= nr < 64 and 0 <= nc < 64:\n yield nr, nc\n\n # 4. Iterate over all cells in the grid to identify all \"valleys\".\n valleys = []\n for r in range(64):\n for c in range(64):\n is_valley = True\n for nr, nc in get_neighbors(r, c):\n if grid[nr][nc] <= grid[r][c]:\n is_valley = False\n break\n if is_valley:\n valleys.append((r, c))\n\n # 5. Traverse and count all valid \"uphill paths\" originating from each valley.\n # We use a Dynamic Programming approach processing cells in descending order \n # to efficiently count paths and avoid recursion limits.\n cells = []\n for r in range(64):\n for c in range(64):\n cells.append((grid[r][c], r, c))\n cells.sort(reverse=True)\n \n paths_from = [[1] * 64 for _ in range(64)]\n for val, r, c in cells:\n for nr, nc in get_neighbors(r, c):\n if grid[nr][nc] > grid[r][c]:\n paths_from[r][c] += paths_from[nr][nc]\n \n # 6. Sum the total number of uphill paths across all valleys.\n total_uphill_paths = 0\n for vr, vc in valleys:\n total_uphill_paths += paths_from[vr][vc]\n\n # 7. Verify that the total number of uphill paths is exactly 8065.\n if total_uphill_paths != 8065:\n print(f\"Error: Expected exactly 8065 uphill paths, but found {total_uphill_paths}.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()", "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.", "ref_solution": "Answer: $2n^2-2n+1$\n\n\\paragraph{Bound.}\nThe lower bound is established as follows:\n\\begin{itemize}\n \\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$.\n \\item There is always at least one uphill path of length $1$, namely the single cell containing $1$ (or indeed any valley).\n\\end{itemize}\nSumming these yields at least $2n^2-2n+1$ uphill paths.\n\n\\paragraph{Construction.}\nFor 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.) \n\nPlace $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. \n\nBecause 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. \n\nBy 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."} | |
| {"split": "construction", "source": "IMO-2020-P4", "category": "Graph Theory", "id": "IMO-2020-P4-33", "query": "There is an integer $n > 1$. There are $n^2$ stations on a slope of a mountain, all at different altitudes. Each of two cable car companies, A and B, operates $k$ cable cars; each cable car provides a transfer from one of the stations to a higher one (with no intermediate stops). The $k$ cable cars of A have $k$ different starting points and kdifferent finishing points, and a cable car which starts higher also finishes higher. The same conditions hold for B. We say that two stations are linked by a company if one can start from the lower station and reach the higher one by using one or more cars of that company (no other movements between stations are allowed). Determine the smallest positive integer $k$ for which one can guarantee that there are\\ntwo stations that are linked by both companies.", "ref_answer": "$k=n^2-n+1$", "instruction": "For the specific case $n=33$, determine the maximum number of cable cars $k$ that each company can operate without creating any pair of stations linked by both companies. Provide an explicit construction for this maximum case.\n\nConstruction requirements:\n- The $33^2 = 1089$ stations are numbered 1 to 1089 from lowest to highest altitude.\n- Output a single Python expression that evaluates to a tuple of two sets: `(A_lines, B_lines)`.\n- `A_lines` and `B_lines` are sets of tuples `(i, j)`, representing a cable car line from station `i` to station `j` for company A and B respectively.\n- The configuration must satisfy all problem constraints for valid cable car operations (distinct start/end points, and a cable car starting higher finishes higher).\n- The number of cars for each company must be exactly $k$ (the maximum possible counter-example size).\n- Put ONLY the Python expression inside the construction block. Do not include any markdown formatting, explanations, or surrounding tags other than `<construct>...</construct>`.", "ref_construction": "({(i, i + 1) for i in range(1, 1090) if i % 33 != 0}, {(i, i + 33) for i in range(1, 1057)})", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input\")\n return\n \n try:\n # Parse the payload directly as a Python expression.\n # eval is used because the reference construction uses comprehensions and range().\n data = eval(payload)\n except Exception as e:\n print(f\"Failed to parse Python expression: {e}\")\n return\n\n if type(data) is not tuple or len(data) != 2:\n print(\"Parsed object is not a tuple of exactly two elements\")\n return\n \n A_lines, B_lines = data\n\n for name, lines in [(\"A_lines\", A_lines), (\"B_lines\", B_lines)]:\n if type(lines) is not set:\n print(f\"{name} is not a set\")\n return\n for item in lines:\n if type(item) is not tuple or len(item) != 2:\n print(f\"An item in {name} is not a tuple of exactly two elements\")\n return\n u, v = item\n if type(u) is not int or type(v) is not int:\n print(f\"An item in {name} contains non-integers\")\n return\n \n if len(A_lines) != 1056:\n print(f\"A_lines has {len(A_lines)} elements, expected 1056\")\n return\n if len(B_lines) != 1056:\n print(f\"B_lines has {len(B_lines)} elements, expected 1056\")\n return\n\n for name, lines in [(\"A_lines\", A_lines), (\"B_lines\", B_lines)]:\n u_set = set()\n v_set = set()\n sorted_lines = sorted(list(lines), key=lambda x: x[0])\n prev_v = -1\n \n for u, v in sorted_lines:\n if not (1 <= u <= 1089 and 1 <= v <= 1089):\n print(f\"Station out of range in {name}: ({u}, {v})\")\n return\n if u >= v:\n print(f\"Invalid transfer in {name}: ({u}, {v}), must be u < v\")\n return\n if u in u_set:\n print(f\"Duplicate starting point {u} in {name}\")\n return\n u_set.add(u)\n if v in v_set:\n print(f\"Duplicate finishing point {v} in {name}\")\n return\n v_set.add(v)\n if v <= prev_v:\n print(f\"Monotonicity violated in {name}: sequence of v is not strictly increasing.\")\n return\n prev_v = v\n\n def get_transitive_closure(lines):\n adj = {u: v for u, v in lines}\n closure = set()\n for start_node in adj:\n curr = start_node\n while curr in adj:\n nxt = adj[curr]\n closure.add((start_node, nxt))\n curr = nxt\n return closure\n\n A_closure = get_transitive_closure(A_lines)\n B_closure = get_transitive_closure(B_lines)\n \n intersection = A_closure.intersection(B_closure)\n if intersection:\n example = list(intersection)[0]\n print(f\"Intersection is not empty. Found linked pairs in both companies, e.g., {example}.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()", "grading_guidelines": "(Partial) 1. Observed/modelled each company’s system as a directed graph on the stations, and correctly deduced from the “order-preserving” and “distinct start/endpoints” conditions that every vertex has indegree ≤1 and outdegree ≤1, hence each connected component is a path (or isolated vertex). 2. Derived the component count formula for one company: with k edges on n^2 vertices and components being paths, the number of connected components equals n^2−k. 3. Gave a correct extremal/pigeonhole step in one graph: from n^2=(n−1)(n+1)+1 and having only n−1 components, concluded that some component has at least n+1 vertices. (Almost) 1. Proved that k=n^2−n+1 is sufficient using the path-component structure and pigeonhole principle, but made a small counting slip (e.g. wrote “at most n−1 components” or miscomputed n^2−k) while the intended argument clearly yields the correct bound. 2. Presented the full sufficiency proof and the idea of a counterexample for k=n^2−n, but did not fully describe/verify the construction (or verified it only for one small n) while the generalization is immediate. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "ref_solution": "Answer: $k = n^2 - n + 1$.\n\nWhen $k = n^2-n$, a valid construction exists for $n=4$ which generalizes readily, demonstrating that this value is not sufficient. \n\nTo see that $k = n^2-n+1$ is sufficient, view $A$ and $B$ as graphs whose vertices are the $n^2$ stations and whose edges are the cable cars. For each company, the condition that a cable car starting higher also finishes higher, with all starting points and finishing points being distinct, implies that the connected components of these graphs are paths (possibly with $0$ edges; the direction of these edges is irrelevant). \n\nNow, if $k = n^2-n+1$, it follows that $A$ and $B$ each have exactly $n^2 - k = n-1$ connected components. Since there are $n^2$ vertices in total and $n^2 = (n-1)(n+1) + 1$, by the Pigeonhole Principle, some component of $A$ has at least $n+1$ vertices. Because graph $B$ has only $n-1$ connected components, this component of $A$ must contain two vertices that belong to the same component of $B$. These two stations are therefore linked by both companies, as desired."} | |
| {"split": "construction", "source": "IMO-2016-P2", "category": "Existence and Construction", "id": "IMO-2016-P2", "query": "Find all integers n for which each cell of $n \\times n$ table can be filled with one of the letters I, M and O in such a way that:\n• In each row and column, one third of the entries are I, one third are M and one third are O; and\n• in any diagonal, if the number of entries on the diagonal is a multiple of three, then one third of the entries are I, one third are M and one third are O.\nNote that an $n \\times n$ table has $4n − 2$ diagonals.", "ref_answer": "The answer is $n$ divisible by $9$.", "ref_solution": "The answer is that $n$ must be divisible by $9$.\n\nFirst, we construct a valid table for $n=9$. We can fill a $9 \\times 9$ table as follows:\n$$\n\\begin{array}{|ccc|ccc|ccc|}\n\\hline\nI & I & I & M & M & M & O & O & O \\\\\nM & M & M & O & O & O & I & I & I \\\\\nO & O & O & I & I & I & M & M & M \\\\\n\\hline\nI & I & I & M & M & M & O & O & O \\\\\nM & M & M & O & O & O & I & I & I \\\\\nO & O & O & I & I & I & M & M & M \\\\\n\\hline\nI & I & I & M & M & M & O & O & O \\\\\nM & M & M & O & O & O & I & I & I \\\\\nO & O & O & I & I & I & M & M & M \\\\\n\\hline\n\\end{array}\n$$\nThis pattern can be extended to any $n$ that is a multiple of $9$ by tiling the grid with this $9 \\times 9$ block.\n\nNow we prove that $9 \\mid n$ is a necessary condition. From the condition on the rows and columns, $n$ must be a multiple of $3$. Let $n = 3k$. We can partition the $n \\times n$ grid into $k^2$ sub-boxes, each of size $3 \\times 3$. \n\nWe say a multiset of squares is *clean* if the letters I, M, and O appear an equal number of times among them (i.e., each letter constitutes exactly one third of the entries). Note that the multiset union of clean multisets is also clean.\n\nConsider the following sets of squares, all of which are clean by the problem statement:\n1. All columns with indices congruent to $2 \\pmod 3$.\n2. All rows with indices congruent to $2 \\pmod 3$.\n3. All $4k-2$ diagonals whose lengths are multiples of $3$.\n\nTake the multiset union of all these clean sets. We determine how many times each cell in the $n \\times n$ grid is covered by this union.\n- The center cell of each $3 \\times 3$ sub-box (which lies at the intersection of a row indexed $2 \\pmod 3$ and a column indexed $2 \\pmod 3$) is covered exactly four times: once by its row, once by its column, and twice by the two diagonals passing through it. (The diagonals passing through $(x, y)$ where $x \\equiv 2 \\pmod 3$ and $y \\equiv 2 \\pmod 3$ have lengths that are multiples of $3$).\n- Every other cell in the grid is covered exactly once by this union.\n\nSince the entire grid is clean (for instance, as the union of all its columns), the multiset consisting of the entire grid covered once is clean. The multiset union we constructed is also clean. Removing the entire grid from our multiset union leaves exactly the center squares of the $k^2$ sub-boxes, each covered exactly three times. \n\nBecause removing a clean multiset from another clean multiset yields a clean multiset, the set of the $k^2$ center squares (taken three times) is clean. This implies that the set of the $k^2$ center squares taken once is also clean. For this set of $k^2$ squares to be clean, its total number of elements must be divisible by $3$. Thus, $3 \\mid k^2$, which implies $3 \\mid k$. Since $n = 3k$, we conclude that $9 \\mid n$, as desired.", "grading_guidelines": "(Partial) 1. Observed from the row/column condition that 3 | n (each row/column has n/3 of each letter). 2. Gave a correct construction for n = 9 (or another explicit n divisible by 9), and indicated how to tile/extend it to all n multiple of 9. 3. Introduced the key “clean multiset” (equal numbers of I,M,O) viewpoint and correctly noted that multiset unions/differences of clean multisets are clean. (Almost) 1. Proved the necessity 9 | n using the 3×3 block/clean-multiset counting idea, but made a localized counting error in the coverage multiplicities (e.g. missed that the special cells are covered 4 times / others once) while the intended conclusion 9 | n is still clearly supported. 2. Completed the main reduction to showing the k^2 center cells form a clean set and hence 3 | k, but did not fully justify one of: (i) why the relevant diagonals through those cells have length multiple of 3, or (ii) why subtracting the whole grid from the union preserves cleanliness. 3. Gave the construction for all n multiple of 9 and the argument that n must be a multiple of 3, and outlined the final step to force 9 | n via the center-cell multiset, but left the last divisibility inference (3 | k^2 ⇒ 3 | k) or an equivalent concluding step insufficiently written.", "instruction": "For the smallest feasible integer $n > 0$, construct a valid $n \\times n$ table satisfying the given conditions.\n\nRequirements for the construction:\n- Represent the table as a Python-literal list of lists of strings, where each string is \"I\", \"M\", or \"O\".\n- The table must satisfy all row, column, and diagonal conditions for the chosen $n$.\n- Include exactly one construction block and put ONLY the Python literal matrix between the tags:\n<construct>\n</construct>\n- Do not use code fences. Do not put any extra text inside <construct>...</construct>.", "ref_construction": "[[\"I\", \"I\", \"I\", \"M\", \"M\", \"M\", \"O\", \"O\", \"O\"], [\"M\", \"M\", \"M\", \"O\", \"O\", \"O\", \"I\", \"I\", \"I\"], [\"O\", \"O\", \"O\", \"I\", \"I\", \"I\", \"M\", \"M\", \"M\"], [\"I\", \"I\", \"I\", \"M\", \"M\", \"M\", \"O\", \"O\", \"O\"], [\"M\", \"M\", \"M\", \"O\", \"O\", \"O\", \"I\", \"I\", \"I\"], [\"O\", \"O\", \"O\", \"I\", \"I\", \"I\", \"M\", \"M\", \"M\"], [\"I\", \"I\", \"I\", \"M\", \"M\", \"M\", \"O\", \"O\", \"O\"], [\"M\", \"M\", \"M\", \"O\", \"O\", \"O\", \"I\", \"I\", \"I\"], [\"O\", \"O\", \"O\", \"I\", \"I\", \"I\", \"M\", \"M\", \"M\"]]", "verify_code": "import sys\nimport ast\n\ndef main():\n # Read the raw input from stdin\n try:\n input_data = sys.stdin.read().strip()\n if not input_data:\n print(\"Error: Empty input\")\n return\n # Parse the input as a Python literal (list of lists of strings)\n matrix = ast.literal_eval(input_data)\n except Exception as e:\n print(f\"Error: Could not parse input as Python literal: {e}\")\n return\n\n # Basic structure check\n if not isinstance(matrix, list) or not all(isinstance(row, list) for row in matrix):\n print(\"Error: Input is not a list of lists\")\n return\n \n # Smallest feasible n is 9\n n = len(matrix)\n if n != 9:\n print(f\"Error: The smallest feasible integer n is 9, but the provided matrix is {n}x{len(matrix[0]) if n > 0 else 0}\")\n return\n \n # Check that all rows have length n and all entries are one of \"I\", \"M\", \"O\"\n for r, row in enumerate(matrix):\n if len(row) != n:\n print(f\"Error: Row {r} has length {len(row)} instead of {n}\")\n return\n for c, val in enumerate(row):\n if val not in (\"I\", \"M\", \"O\"):\n print(f\"Error: Invalid character '{val}' at row {r}, column {c}\")\n return\n\n # Row and column requirements: each letter appears n/3 times (3 times for n=9)\n target_count = n // 3\n for i in range(n):\n # Row check\n row = matrix[i]\n for letter in (\"I\", \"M\", \"O\"):\n if row.count(letter) != target_count:\n print(f\"Error: Row {i} does not have exactly {target_count} of letter '{letter}'\")\n return\n \n # Column check\n col = [matrix[j][i] for j in range(n)]\n for letter in (\"I\", \"M\", \"O\"):\n if col.count(letter) != target_count:\n print(f\"Error: Column {i} does not have exactly {target_count} of letter '{letter}'\")\n return\n\n # Diagonal checks: for any diagonal with length L divisible by 3, \n # each letter must appear L/3 times.\n \n # Main-direction diagonals: cells (i, j) where i - j = k\n # k ranges from -(n-1) to (n-1)\n for k in range(-(n-1), n):\n diag = [matrix[i][i-k] for i in range(n) if 0 <= i-k < n]\n L = len(diag)\n if L % 3 == 0:\n for letter in (\"I\", \"M\", \"O\"):\n if diag.count(letter) != L // 3:\n print(f\"Error: Main-direction diagonal (i-j={k}) of length {L} fails the distribution rule for letter '{letter}'\")\n return\n\n # Anti-direction diagonals: cells (i, j) where i + j = k\n # k ranges from 0 to 2n-2\n for k in range(2 * n - 1):\n diag = [matrix[i][k-i] for i in range(n) if 0 <= k-i < n]\n L = len(diag)\n if L % 3 == 0:\n for letter in (\"I\", \"M\", \"O\"):\n if diag.count(letter) != L // 3:\n print(f\"Error: Anti-direction diagonal (i+j={k}) of length {L} fails the distribution rule for letter '{letter}'\")\n return\n\n # If all checks pass\n print(\"True\")\n\nif __name__ == \"__main__\":\n main()"} | |
| {"split": "construction", "source": "IMO-2014-P2", "category": "Extremal Problems", "id": "IMO-2014-P2-233", "query": "Let $n \\\\geq 2$ be an integer. Consider an $n \\\\times n$ chessboard consisting of $n^2$ unit squares. A configuration of n rooks on this board is peaceful if every row and every column contains exactly one rook. Find the greatest positive integer $k$ such that, for each\\npeaceful configuration of $n$ rooks, there is a $k \\\\times k$ square which does not contain a rook on any of its $k^2$ unit squares.", "ref_answer": "$k = \\\\lfloor \\\\sqrt(n-1) \\\\rfloor $", "instruction": "For the specific case $n=233$, construct a peaceful configuration of $n$ rooks and find the minimum positive integer $l$ such that every $l \\times l$ square contains at least one rook.\n\nConstruction format requirements:\n- Output a single Python dictionary with keys: `'l'` and `'rooks'`.\n- `'l'` is the minimum positive integer (an integer).\n- `'rooks'` is a list of 233 integers, where the $r$-th integer (0-indexed) represents the column index of the rook in row $r$. Both row and column indices are integers from $0$ to $232$.\n- The configuration must be peaceful, meaning every row and every column contains exactly one rook.\n- Every $l \\times l$ square in the $233 \\times 233$ grid must contain at least one rook.\n- Put ONLY the Python literal dictionary inside the construction block.", "ref_construction": "{\"l\": 16, \"rooks\": [dict([(16 * i + j - 23, 16 * j + i) for i in range(16) for j in range(16) if 16 * i + j >= 23 and 16 * j + i <= 232] + list(zip(sorted([16 * i - 9 for i in range(9, 16)] + [16 * i - 8 for i in range(1, 16)]), sorted([16 * j for j in range(15)] + [16 * j + 1 for j in range(7)]))))[r] for r in range(233)]}", "verify_code": "import sys\nimport ast\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Error: Empty input.\")\n return\n\n try:\n # The instruction and user intent specify a Python literal parsed with ast.literal_eval.\n data = ast.literal_eval(payload)\n except Exception as e_lit:\n # Fallback to eval with restricted builtins strictly to maintain compatibility \n # with the provided ref_construction, which uses comprehensions and specific builtins.\n try:\n allowed_builtins = {\n 'dict': dict,\n 'list': list,\n 'zip': zip,\n 'sorted': sorted,\n 'range': range,\n '__builtins__': {}\n }\n data = eval(payload, allowed_builtins, {})\n except Exception:\n # If the fallback also fails, surface the original literal_eval error.\n print(f\"Parse error: {e_lit}\")\n return\n\n if type(data) is not dict:\n print(\"Error: The construction must be a Python dictionary.\")\n return\n\n if set(data.keys()) != {'l', 'rooks'}:\n print(\"Error: The dictionary must contain exactly the keys 'l' and 'rooks'.\")\n return\n\n l = data['l']\n if type(l) is not int:\n print(\"Error: 'l' must be an integer.\")\n return\n\n if l != 16:\n print(f\"Error: 'l' must be 16 (the mathematically required minimum for n=233), but got {l}.\")\n return\n\n rooks = data['rooks']\n if type(rooks) is not list:\n print(\"Error: 'rooks' must be a list.\")\n return\n\n if len(rooks) != 233:\n print(f\"Error: 'rooks' must contain exactly 233 integers, but got {len(rooks)}.\")\n return\n\n for i, c in enumerate(rooks):\n if type(c) is not int:\n print(f\"Error: Element at index {i} in 'rooks' is not an integer.\")\n return\n if not (0 <= c <= 232):\n print(f\"Error: Element at index {i} in 'rooks' is out of bounds (must be 0-232, got {c}).\")\n return\n\n if len(set(rooks)) != 233:\n print(\"Error: The configuration is not peaceful. There are duplicate column indices in 'rooks'.\")\n return\n\n # Iterate over all possible 16x16 squares in the 233x233 grid.\n # A 16x16 square is defined by row range [R, R+15] and col range [C, C+15]\n # R and C range from 0 to 233 - 16 = 217.\n for R in range(218):\n for C in range(218):\n found = False\n for r in range(R, R + 16):\n if C <= rooks[r] <= C + 15:\n found = True\n break\n if not found:\n print(f\"Error: The 16x16 square at rows {R}-{R+15} and columns {C}-{C+15} is completely empty.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()", "grading_guidelines": "(Partial) 1. Proved the lower bound k ≤ ⌊√(n−1)⌋ by exhibiting (for m=k+1) a peaceful configuration on an m^2×m^2 board with no empty m×m square (e.g. via the explicit permutation j=(i mod m)m+⌊i/m⌋), even if not fully justified that every m×m square meets a rook. 2. Proved the existence part in the form: if n>k^2 then every peaceful configuration has an empty k×k square, by choosing k^2 consecutive rows under the top rook, splitting into k blocks of k rows, fixing k consecutive columns through that rook, and applying pigeonhole to the k resulting k×k squares. 3. Correctly identified the claimed answer k=⌊√(n−1)⌋ and gave a coherent plan for both directions (n>k^2 implies existence; construction for n≤(k+1)^2), with at least one direction carried out rigorously. (Almost) 1. Proved both directions for the extremal value k=⌊√(n−1)⌋, but left a small gap in the construction side: did not fully prove that the constructed m^2×m^2 permutation has the property that every m×m square contains a rook (e.g. the coverage/“forbidden top-left corners” argument incomplete). 2. Proved the sharp construction for size m^2 and the existence proof for n>k^2, but did not justify the adaptation from m^2×m^2 to arbitrary n≤m^2 (e.g. deletion/refilling step or preservation of the “no empty m×m square” property). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "ref_solution": "The answer is $k = \\left\\lfloor \\sqrt{n-1} \\right\\rfloor$. \n\nFirst, we prove that for any $n > k^2$, every peaceful configuration of $n$ rooks contains an empty $k \\times k$ square. Let $R$ be the rook in the topmost row (row $0$). Since $n > k^2$, there are at least $k^2$ rows below $R$. Consider the $k^2$ rows immediately below $R$, and partition them into $k$ blocks of $k$ consecutive rows. Let $c$ be the column containing $R$. We can choose a block of $k$ consecutive columns that includes $c$ (this is possible since $n \\ge k$). The intersection of these $k$ columns with the $k$ blocks of rows forms $k$ squares of size $k \\times k$, aligned vertically directly below the row of $R$. These $k$ squares occupy $k$ columns and $k^2$ rows. Because the configuration is peaceful, these $k$ columns contain exactly $k$ rooks in total across the entire board. One of these rooks is $R$, which is located in the topmost row, outside our $k$ squares. Therefore, the $k$ squares contain at most $k-1$ rooks in total. By the Pigeonhole Principle, at least one of the $k \\times k$ squares must be completely empty.\n\nTo prove this is the maximum possible $k$, we must show that for $m = k+1$, there exists a peaceful configuration of $n \\le m^2$ rooks with no empty $m \\times m$ square. Following the original notation, we first give an explicit construction for an $m^2 \\times m^2$ board showing there may be no empty $m \\times m$ square. \n\nIndex the rows and columns from $0$ to $m^2-1$. We place a rook at $(i, j)$ if and only if $j = (i \\bmod m) \\cdot m + \\lfloor i/m \\rfloor$. \nThis is a peaceful configuration: any $i \\in \\{0, \\dots, m^2-1\\}$ can be written uniquely as $i = a m + b$ with $0 \\le a, b \\le m-1$, placing the rook at $j = b m + a$. The mapping $(a, b) \\mapsto (b, a)$ is a bijection on $\\{0, \\dots, m-1\\}^2$, so each row and column receives exactly one rook.\n\nTo show that this works, consider for each rook drawing an $m \\times m$ square of \"forbidden\" top-left corners whose bottom-right hand corner is the rook. A rook at $(i, j)$ forbids any $m \\times m$ square whose top-left corner $(x, y)$ satisfies $x \\le i \\le x+m-1$ and $y \\le j \\le y+m-1$. We must show that these forbidden regions cover all valid top-left corners $(x, y) \\in [0, m^2-m] \\times [0, m^2-m]$. (Parts of the last $m-1$ columns or rows may not be covered, but they don't matter anyways since a top-left corner cannot be placed there.)\n\nLet $(x, y)$ be an arbitrary valid top-left corner. Write $y = e m + f$ where $0 \\le e \\le m-1$ and $0 \\le f \\le m-1$.\nThe interval $[x, x+m-1]$ consists of $m$ consecutive integers, so it contains exactly one integer $i_1 \\equiv e \\pmod m$. Let $i_1 = a_1 m + e$. The corresponding rook is at $j_1 = e m + a_1$.\nIf $a_1 \\ge f$, then $j_1 \\ge e m + f = y$. Since $a_1 \\le m-1$, we also have $j_1 \\le e m + m - 1 \\le y + m - 1$. Thus, the rook $(i_1, j_1)$ forbids $(x, y)$.\n\nIf $a_1 < f$, then $f > 0$, which implies $e < m-1$ (since $y \\le m^2-m$). The interval $[x, x+m-1]$ also contains exactly one integer $i_2 \\equiv e+1 \\pmod m$. Let $i_2 = a_2 m + e + 1$. The corresponding rook is at $j_2 = (e+1)m + a_2$.\nWe have $j_2 \\ge (e+1)m > e m + f = y$. We need $j_2 \\le y + m - 1 = (e+1)m + f - 1$, which requires $a_2 < f$.\nSince $i_1, i_2 \\in [x, x+m-1]$ and $i_2 \\equiv i_1 + 1 \\pmod m$, we must have either $i_2 - i_1 = 1$ or $i_2 - i_1 = 1 - m$. Substituting $i_1 = a_1 m + e$ and $i_2 = a_2 m + e + 1$, we get $i_2 - i_1 = (a_2 - a_1)m + 1$. Thus, $(a_2 - a_1)m + 1 \\in \\{1, 1-m\\}$, which implies $a_2 - a_1 \\in \\{0, -1\\}$. In either case, $a_2 \\le a_1$. Since we assumed $a_1 < f$, it follows that $a_2 < f$. Thus, the rook $(i_2, j_2)$ forbids $(x, y)$. In all cases, the $m \\times m$ square contains at least one rook.\n\nFinally, it remains to check that the construction can be adapted for all $n \\le m^2$ (omitting this step is a common mistake). For this, we can delete the bottom $m^2 - n$ rows and the rightmost $m^2 - n$ columns from our $m^2 \\times m^2$ board to get an $n \\times n$ board. In doing so, we may have accidentally deleted some rooks. We can fill in any gaps where we deleted a rook by placing new rooks at the intersections of the empty rows and empty columns in the new $n \\times n$ board to ensure it remains peaceful. Any $m \\times m$ square in this $n \\times n$ board is also an $m \\times m$ square in the original board, meaning it originally contained at least one rook. Because the entire $m \\times m$ square is preserved, the rook it contained was not deleted. Thus, the configuration remains peaceful and has no empty $m \\times m$ square."} | |
| {"split": "construction", "source": "IMO-2004-P3", "category": "Existence and Construction", "id": "IMO-2004-P3", "query": "Define a “hook” to be a figure made up of six unit squares as shown below in the picture, or any of the figures obtained by applying rotations and reflections to this figure.Which $m \times n$ rectangles can be tiled by hooks?", "ref_solution": "The answer is that one requires: $m, n \\notin \\{1,2,5\\}$, and ($3 \\mid m$ or $3 \\mid n$), and ($4 \\mid m$ or $4 \\mid n$). \n\nFirst, we check that all rectangles satisfying these conditions can be tiled by $3 \\times 4$ rectangles (and hence by hooks, since a $3 \\times 4$ rectangle can be tiled by two hooks). If $3 \\mid m$ and $4 \\mid n$, this is clear. Else, suppose $12 \\mid m$ but $3 \\nmid n$ and $4 \\nmid n$. Since $n \\notin \\{1,2,5\\}$ and $n$ is not a multiple of $3$ or $4$, we must have $n \\ge 7$. Any integer $n \\ge 7$ can be written in the form $3x+4y$ for nonnegative integers $x$ and $y$. This permits a tiling of the $m \\times n$ rectangle by partitioning it into $m \\times 3$ and $m \\times 4$ rectangles, each of which can be tiled by $3 \\times 4$ rectangles (since $12 \\mid m$).\n\nWe now prove these conditions are necessary. It is straightforward to see that $m,n \\notin \\{1,2,5\\}$ is necessary, as no combination of hooks can tile rectangles with these dimensions. We thus turn our attention to the divisibility conditions. \n\nEach hook has a \"hole\", and if we associate each hook with the one that fills its hole, we get a bijective pairing of hooks. Thus, the total number of cells is divisible by $12$, and the cells come grouped into two possible shapes, which we will call **tiles** (rotations and reflections permitted). \n\nSuppose for the sake of contradiction there is a tileable rectangle that satisfies $12 \\mid mn$ but fails the condition \"($3 \\mid m$ or $3 \\mid n$) and ($4 \\mid m$ or $4 \\mid n$)\". Since $12 \\mid mn$, $3$ must divide $m$ or $n$, so the failure must be that $4 \\nmid m$ and $4 \\nmid n$. Since $4 \\mid mn$, this implies $m$ and $n$ are both even but not divisible by $4$, so $m \\equiv 2 \\pmod 4$ and $n \\equiv 2 \\pmod 4$. Since $3$ divides $m$ or $n$, we may assume without loss of generality that $3 \\mid m$. Then $m$ is a multiple of $6$ and $n$ is a multiple of $2$, so we can write $m = 6a$ and $n = 2b$. Since $m, n \\equiv 2 \\pmod 4$, both $a$ and $b$ must be odd. Thus, the problem is reduced to proving that if a $6a \\times 2b$ rectangle is tiled by these tiles, then at least one of $a$ and $b$ is even (which would contradict that $a$ and $b$ are both odd).\n\nNote that the tiles can be classified into two types:\n**First type**: These tiles have exactly four columns, each with exactly three cells (an odd number). Moreover, all rows have an even number of cells (either $2$ or $4$).\n**Second type**: Vice-versa. These tiles have exactly four rows, each with exactly three cells (an odd number). Moreover, all columns have an even number of cells (either $2$ or $4$).\n\nWe claim that any tiling uses an even number of each type of tile, which is enough to show that the total number of tiles, $ab$, is even, meaning at least one of $a$ and $b$ is even. \n\nBy symmetry, it suffices to prove there is an even number of first-type tiles. Color red every fourth column of the rectangle. The number of cells colored red is even, because the rectangle has an even height of $6a$, meaning each column contains an even number of cells. \nThe tiles of the second type have an even number of cells in every column, so they must cover an even number of red cells. \nSince a tile of the first type is connected and has exactly four columns, it spans exactly four consecutive columns, meaning exactly one of its columns is colored red. Because each of its columns contains exactly three cells, a tile of the first type covers exactly $3$ red cells, which is an odd number. \n\nSince the total number of red cells is even, and the second-type tiles cover an even number of red cells, the number of first-type tiles must be even. By a symmetric argument coloring every fourth row, the number of second-type tiles is also even. Hence, the total number of tiles $ab$ is even, completing the proof.", "grading_guidelines": "(Partial) 1. Observed that a 3×4 rectangle can be tiled by two hooks, and reduced the sufficiency part to tiling the m×n rectangle by 3×4 rectangles (e.g. via splitting n as 3x+4y when 12|m, or the symmetric case). 2. Proved a necessary area/divisibility condition such as: in any tiling the hooks can be paired into 12-cell “tiles”, hence 12 | mn (or equivalently 3|mn and 4|mn). 3. Gave a correct obstruction for small side lengths, e.g. proved that no rectangle with m∈{1,2,5} or n∈{1,2,5} can be tiled (with a valid local/invariant argument, not just examples). (Almost) 1. Established the full characterization m,n∉{1,2,5}, (3|m or 3|n), (4|m or 4|n), and proved the construction for all such rectangles by reducing to 3×4 blocks, but left a small gap in the decomposition step (e.g. the claim that every n≥7 can be written as 3x+4y, or a boundary case when swapping roles of m,n). 2. Proved necessity via pairing hooks into 12-cell tiles and the parity-of-types coloring argument (every 4th row/column) to rule out the case m≡n≡2 (mod 4), but did not fully justify one local structural claim about the two tile types (e.g. why each type covers an odd/even number of marked cells, or why a first-type tile meets exactly one marked column). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "After solving the problem, output a finite list of construction units.\n\nDefinition (construction units). Let the output be a finite set of 2D grids U={U_1,...,U_t} (represented by a Python list [U_1,...,U_t]). For every m×n rectangle R,\nR is tileable by hooks if and only if R is tileable by translated/rotated/reflected copies of elements of U.\n\nHook-level encoding requirement. In each unit grid U_i, every positive integer label must appear exactly 6 times and must form (up to rotation/reflection) a hook; different labels represent different hooks. Each U_i must contain at least two hooks (i.e., at least 12 occupied cells).\n\nNon-redundancy requirement. For all i!=j, U_i must not be tileable by translated/rotated/reflected copies of U_j alone (and vice versa).\n\nOutput format requirements:\n- Include exactly one construction block and put ONLY a Python 3D list literal (a list of 2D grids) between the tags:\n<construct>\n<python_literal_3d_grid_list>\n</construct>\n- The 3D literal must have the form [grid1, grid2, ...], where each gridk is a Python list-of-lists (a 2D matrix) encoding one construction unit.\n- Do not use code fences and do not put any extra text inside <construct>...</construct>.", "ref_construction": "[\n [\n [1, 1, 1, 2],\n [1, 2, 1, 2],\n [1, 2, 2, 2]\n ],\n [\n [0, 1, 1, 1],\n [0, 1, 2, 1],\n [2, 1, 2, 0],\n [2, 2, 2, 0]\n ]\n]", "verify_code": "import ast\nimport sys\n\n\nBASE_UNITS = [\n [\n [1, 1, 1, 2],\n [1, 2, 1, 2],\n [1, 2, 2, 2],\n ],\n [\n [0, 1, 1, 1],\n [0, 1, 2, 1],\n [2, 1, 2, 0],\n [2, 2, 2, 0],\n ],\n]\n\n\ndef _is_int(value) -> bool:\n return isinstance(value, int) and not isinstance(value, bool)\n\n\ndef _fail() -> None:\n print(\"False\")\n raise SystemExit(0)\n\n\ndef _parse_units(text: str):\n try:\n value = ast.literal_eval(text)\n except Exception:\n _fail()\n if not isinstance(value, list) or len(value) != 2:\n _fail()\n return value\n\n\ndef _validate_grid(grid):\n if not isinstance(grid, list) or not grid:\n _fail()\n if any(not isinstance(row, list) for row in grid):\n _fail()\n width = len(grid[0])\n if width == 0 or any(len(row) != width for row in grid):\n _fail()\n\n has_positive = False\n for row in grid:\n for value in row:\n if not _is_int(value) or value < 0:\n _fail()\n if value > 0:\n has_positive = True\n if not has_positive:\n _fail()\n return grid\n\n\ndef _trim_zero_border(grid):\n rows = [i for i, row in enumerate(grid) if any(v > 0 for v in row)]\n cols = [j for j in range(len(grid[0])) if any(grid[i][j] > 0 for i in range(len(grid)))]\n if not rows or not cols:\n _fail()\n r1, r2 = rows[0], rows[-1]\n c1, c2 = cols[0], cols[-1]\n return [row[c1 : c2 + 1] for row in grid[r1 : r2 + 1]]\n\n\ndef _rotate_90(grid):\n h = len(grid)\n w = len(grid[0])\n return [[grid[h - 1 - r][c] for r in range(h)] for c in range(w)]\n\n\ndef _reflect(grid):\n return [list(reversed(row)) for row in grid]\n\n\ndef _all_transforms(grid):\n seen = set()\n out = []\n cur = [row[:] for row in grid]\n for _ in range(4):\n for cand in (cur, _reflect(cur)):\n sig = tuple(tuple(v for v in row) for row in cand)\n if sig not in seen:\n seen.add(sig)\n out.append(cand)\n cur = _rotate_90(cur)\n return out\n\n\ndef _canonical_label_signature(grid):\n mapping = {}\n next_label = 1\n out = []\n for row in grid:\n new_row = []\n for value in row:\n if value == 0:\n new_row.append(0)\n continue\n if value not in mapping:\n mapping[value] = next_label\n next_label += 1\n new_row.append(mapping[value])\n out.append(tuple(new_row))\n return tuple(out)\n\n\ndef _unit_signature(grid):\n checked = _validate_grid(grid)\n trimmed = _trim_zero_border(checked)\n return _canonical_label_signature(trimmed)\n\n\ndef _variant_signature_set(base_grid):\n trimmed = _trim_zero_border(base_grid)\n return {\n _canonical_label_signature(_trim_zero_border(variant))\n for variant in _all_transforms(trimmed)\n }\n\n\ndef _can_match_bijection(candidate_to_base):\n used = set()\n\n def _dfs(i: int) -> bool:\n if i == len(candidate_to_base):\n return True\n for base_idx in candidate_to_base[i]:\n if base_idx in used:\n continue\n used.add(base_idx)\n if _dfs(i + 1):\n return True\n used.remove(base_idx)\n return False\n\n return _dfs(0)\n\n\ndef main() -> None:\n text = sys.stdin.read()\n if not text:\n _fail()\n\n units = _parse_units(text)\n\n base_variants = [_variant_signature_set(unit) for unit in BASE_UNITS]\n\n candidate_matches = []\n for unit in units:\n sig = _unit_signature(unit)\n matches = [idx for idx, variants in enumerate(base_variants) if sig in variants]\n if not matches:\n _fail()\n candidate_matches.append(matches)\n\n if not _can_match_bijection(candidate_matches):\n _fail()\n\n print(\"True\")\n\n\nif __name__ == \"__main__\":\n main()\n", "ref_answer": "The answer is that one requires:\n$$\n\\bigl({1,2,5}\\cap{m,n}=\\varnothing\\bigr)\\ \\land\\ \\bigl(3\\mid m\\ \\lor\\ 3\\mid n\\bigr)\\ \\land\\ \\bigl(4\\mid m\\ \\lor\\ 4\\mid n\\bigr).\n$$ e.g., (m,n) = (24,19), (10,12), (6,8)."} | |
| {"split": "construction", "source": "USAMO-2024-P4", "category": "Counting", "id": "USAMO-2024-P4", "query": "Let $m$ and $n$ be positive integers. A circular necklace contains $mn$ beads, each either red or blue. It turned out that no matter how the necklace was cut into $m$ blocks of $n$ consecutive beads, each block had a distinct number of red beads. Determine, with proof, all possible values of the ordered pair $(m, n)$.", "ref_answer": "$m \\leq n + 1$.", "ref_solution": "The possible values for the ordered pair $(m, n)$ are exactly those for which $m \\leq n+1$.\n\n**Necessity:**\nSuppose a necklace of $mn$ beads is cut into $m$ blocks of length $n$. The number of red beads in any block must be an integer between $0$ and $n$ inclusive. There are exactly $n+1$ possible values for this count. Since each of the $m$ blocks must have a distinct number of red beads, we must have $m \\leq n+1$.\n\n**Construction for $m = n+1$:**\nFor concreteness, here is the construction for $n=4$, which naturally generalizes. The beads are listed in reading order as an array with $n+1$ rows and $n$ columns. Four of the blue beads have been labeled $B_1, \\dots, B_n$ to make them easier to track as they move.\n\\[\nT_0 = \\begin{bmatrix}\n\\color{red}R & \\color{red}R & \\color{red}R & \\color{red}R \\\\\n\\color{red}R & \\color{red}R & \\color{red}R & \\color{blue}B_1 \\\\\n\\color{red}R & \\color{red}R & \\color{blue}B & \\color{blue}B_2 \\\\\n\\color{red}R & \\color{blue}B & \\color{blue}B & \\color{blue}B_3 \\\\\n\\color{blue}B & \\color{blue}B & \\color{blue}B & \\color{blue}B_4\n\\end{bmatrix}.\n\\]\nTo prove this construction works, it suffices to consider the $n$ cuts $T_0, T_1, \\dots, T_{n-1}$, where $T_i$ represents the blocks formed by starting the cut $i$ beads later. We must show that each row in $T_i$ has a distinct red count:\n\\[\nT_1 = \\begin{bmatrix}\n\\color{red}R & \\color{red}R & \\color{red}R & \\color{red}R \\\\\n\\color{red}R & \\color{red}R & \\color{blue}B_1 & \\color{red}R \\\\\n\\color{red}R & \\color{blue}B & \\color{blue}B_2 & \\color{red}R \\\\\n\\color{blue}B & \\color{blue}B & \\color{blue}B_3 & \\color{blue}B \\\\\n\\color{blue}B & \\color{blue}B & \\color{blue}B_4 & \\color{red}R\n\\end{bmatrix} \\quad\nT_2 = \\begin{bmatrix}\n\\color{red}R & \\color{red}R & \\color{red}R & \\color{red}R \\\\\n\\color{red}R & \\color{blue}B_1 & \\color{red}R & \\color{red}R \\\\\n\\color{blue}B & \\color{blue}B_2 & \\color{red}R & \\color{blue}B \\\\\n\\color{blue}B & \\color{blue}B_3 & \\color{blue}B & \\color{blue}B \\\\\n\\color{blue}B & \\color{blue}B_4 & \\color{red}R & \\color{red}R\n\\end{bmatrix} \\quad\nT_3 = \\begin{bmatrix}\n\\color{red}R & \\color{red}R & \\color{red}R & \\color{red}R \\\\\n\\color{blue}B_1 & \\color{red}R & \\color{red}R & \\color{blue}B \\\\\n\\color{blue}B_2 & \\color{red}R & \\color{blue}B & \\color{blue}B \\\\\n\\color{blue}B_3 & \\color{blue}B & \\color{blue}B & \\color{blue}B \\\\\n\\color{blue}B_4 & \\color{red}R & \\color{red}R & \\color{red}R\n\\end{bmatrix}.\n\\]\nWe can construct a table showing for each $0 \\le k \\le n$ the number of red beads in row $k$ of $T_i$ (where the rows are indexed from $k=n$ at the top down to $k=0$ at the bottom):\n\\[\n\\begin{array}{c|cccc}\nk & T_0 & T_1 & T_2 & T_3 \\\\ \\hline\nk=4 & 4 & 4 & 4 & 4 \\\\\nk=3 & 3 & 3 & 3 & 2 \\\\\nk=2 & 2 & 2 & 1 & 1 \\\\\nk=1 & 1 & 0 & 0 & 0 \\\\\nk=0 & 0 & 1 & 2 & 3\n\\end{array}.\n\\]\nThis suggests the following explicit formula for the number of red cells in row $k$ of $T_i$ in the general construction:\n\\[\n\\#(\\text{red cells in row } k \\text{ of } T_i) =\n\\begin{cases}\nk & \\text{if } k > i \\\\\nk-1 & \\text{if } i \\ge k > 0 \\\\\ni & \\text{if } k = 0.\n\\end{cases}\n\\]\nThis can be checked straightforwardly. Let the rows of $T_0$ be indexed by $k = n, n-1, \\dots, 0$ from top to bottom. The $k$-th row consists of $k$ red beads followed by $n-k$ blue beads. When we shift the cut by $i$ beads ($0 \\le i \\le n-1$), the new $k$-th block consists of the last $n-i$ beads of the original $k$-th row and the first $i$ beads of the original $(k-1)$-th row (with indices taken modulo $n+1$, so the row below $k=0$ is $k=n$). \n\nWe count the number of red beads in this new block:\n- For $k > 0$, the original $k$-th row starts with $k$ red beads. Removing the first $i$ beads leaves $\\max(0, k-i)$ red beads. The original $(k-1)$-th row starts with $k-1$ red beads. Taking its first $i$ beads gives $\\min(i, k-1)$ red beads. The total number of red beads is $\\max(0, k-i) + \\min(i, k-1)$.\n - If $k > i$, this sum is $(k-i) + i = k$.\n - If $0 < k \\le i$, this sum is $0 + (k-1) = k-1$.\n- For $k = 0$, the original $0$-th row has no red beads, so the first part contributes $0$. The next row in reading order is the $n$-th row, which consists of $n$ red beads. Since $i \\le n-1 < n$, taking its first $i$ beads gives exactly $i$ red beads. The total is $i$.\n\nThus, for each $i$, the sequence of red counts from bottom to top (as $k$ goes from $0$ to $n$) is exactly $(i, 0, 1, \\dots, i-1, i+1, \\dots, n)$. These are exactly the integers from $0$ to $n$, meaning the counts are all distinct. This completes the construction for $m = n+1$.\n\n**Construction for general $m \\le n+1$:**\nFix $m \\le n+1$. Take the construction for $(m, m-1)$ and add $n+1-m$ cyan beads to the start of each row. For example, if $n = 7$ and $m = 5$, then the new construction is\n\\[\nT = \\begin{bmatrix}\n\\color{cyan}C & \\color{cyan}C & \\color{cyan}C & \\color{red}R & \\color{red}R & \\color{red}R & \\color{red}R \\\\\n\\color{cyan}C & \\color{cyan}C & \\color{cyan}C & \\color{red}R & \\color{red}R & \\color{red}R & \\color{blue}B_1 \\\\\n\\color{cyan}C & \\color{cyan}C & \\color{cyan}C & \\color{red}R & \\color{red}R & \\color{blue}B & \\color{blue}B_2 \\\\\n\\color{cyan}C & \\color{cyan}C & \\color{cyan}C & \\color{red}R & \\color{blue}B & \\color{blue}B & \\color{blue}B_3 \\\\\n\\color{cyan}C & \\color{cyan}C & \\color{cyan}C & \\color{blue}B & \\color{blue}B & \\color{blue}B & \\color{blue}B_4\n\\end{bmatrix}.\n\\]\nThis construction works for the same reason. Let $c = n+1-m$. We check the shifts by $i$ beads for $0 \\le i \\le n-1$:\n- If $0 \\le i \\le c$, shifting by $i$ beads removes $i$ cyan beads from the start of each row and brings in $i$ cyan beads from the start of the next row. The red beads in each row remain exactly the same as in the unshifted configuration, so the red counts are distinct.\n- If $c < i \\le n-1$, let $i' = i - c$. Shifting by $i$ beads removes all $c$ cyan beads and the first $i'$ beads of the $(m, m-1)$ construction from each row. It then appends $c$ cyan beads and the first $i'$ beads of the $(m, m-1)$ construction from the next row. The number of red beads in each block is exactly the same as shifting the $(m, m-1)$ construction by $i'$ beads. Since $1 \\le i' \\le m-2$, the $(m, m-1)$ construction guarantees that the red counts are distinct.\n\nTreating cyan as a shade of blue, this provides a valid configuration for any $m \\le n+1$, completing the proof.", "grading_guidelines": "(Partial) 1. Proved the necessary bound m≤n+1 by noting each block has between 0 and n red beads (only n+1 possible counts) and the m counts must be distinct. 2. Gave a correct explicit coloring for the extremal case m=n+1 (e.g. arranging blocks with k red beads for k=0,1,…,n in some cyclic manner) and checked it works for at least the unshifted cut. 3. Made a correct reduction that it suffices to check only the n cyclic shifts of a fixed “row-by-row” representation of the necklace (i.e. start the cut i beads later for i=0,…,n−1). (Almost) 1. Proved m≤n+1 and gave a construction for all m≤n+1, but left a minor gap in verifying that the construction works for every shift (e.g. did not fully justify the red-count formula after shifting by i). 2. Gave a complete construction for m=n+1 and correctly derived the red counts for k>0, but did not handle the wrap-around/boundary case k=0 (or the case i=0 vs i=n−1) needed to conclude all counts 0,1,…,n occur. 3. Constructed the general m≤n+1 case by modifying the m=n+1 (or (m,m−1)) construction, but did not justify why the added beads do not create equal red counts for some range of shifts.", "instruction": "For the specific case $n=4$, determine the maximum possible integer $m$ for which such a necklace exists. Provide an explicit construction of the necklace for this maximum $m$.\n\nConstruction requirements:\n- Output a single Python list of lists representing the $m \\times n$ blocks of the necklace.\n- Use 1 for red beads and 0 for blue beads.\n- The matrix represents the necklace cut into $m$ blocks of size $n$ at a specific starting position (shift 0). Flattening the matrix row-by-row (row 0, then row 1, etc.) yields the full circular sequence of beads.\n- The construction must satisfy the problem condition: for every possible way of cutting the circular necklace into $m$ blocks of length $n$ (which corresponds to cyclically shifting the flattened sequence by any offset $k \\in \\{0, \\dots, n-1\\}$ before partitioning), the number of red beads (1s) in the resulting $m$ blocks must be pairwise distinct.\n- The verifier will check that you have used the largest possible value for $m$ and that the distinctness condition holds for all valid cuts.\n- Put ONLY the Python literal inside the construction block.", "ref_construction": "[[0, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 1, 1],\n [0, 1, 1, 1],\n [1, 1, 1, 1]]", "verify_code": "import sys\nimport ast\n\ndef verify_necklace():\n \"\"\"\n Verifies the construction of a circular necklace with mn beads (m blocks of size n)\n such that for any cut into m blocks, the number of red beads in each block is distinct.\n Target case: n=4, max m=5.\n \"\"\"\n # Read full stdin as the construction payload\n try:\n input_data = sys.stdin.read().strip()\n if not input_data:\n print(\"Error: Input is empty.\")\n return\n \n # Parse strictly as a Python literal (expecting a list of lists)\n matrix = ast.literal_eval(input_data)\n except Exception as e:\n print(f\"Error: Failed to parse input as a Python literal. {e}\")\n return\n\n # 1. Parse the input as a Python list of lists (matrix).\n if not isinstance(matrix, list):\n print(\"Error: Input must be a list of lists.\")\n return\n \n if len(matrix) == 0:\n print(\"Error: Matrix cannot be empty.\")\n return\n\n if not all(isinstance(row, list) for row in matrix):\n print(\"Error: Input must be a list of lists.\")\n return\n\n # 3. Verify that the number of columns (n) is exactly 4.\n target_n = 4\n # 4. Verify that the number of rows (m) is exactly 5 (since max m <= n + 1).\n target_m = 5\n \n m = len(matrix)\n if m != target_m:\n print(f\"Error: Expected {target_m} rows (m) for the maximum possible size, but found {m}.\")\n return\n\n flat_necklace = []\n \n # Validate dimensions and values\n for r_idx, row in enumerate(matrix):\n if len(row) != target_n:\n print(f\"Error: Row {r_idx} has length {len(row)}, expected {target_n}.\")\n return\n \n for c_idx, val in enumerate(row):\n # 2. Verify that the matrix contains only integers 0 and 1.\n # Strict check: reject bools or other types to ensure compliance with 'integers 0 and 1'\n if type(val) is not int or val not in (0, 1):\n print(f\"Error: Invalid value {val} at row {r_idx}, col {c_idx}. Only integers 0 and 1 are allowed.\")\n return\n \n # 5. Flatten the matrix into a single 1D list representing the circular necklace.\n flat_necklace.extend(row)\n\n n = target_n\n total_beads = m * n\n\n # 6. Iterate through shift offsets s from 0 to n-1\n # Checking s in range(n) is sufficient because shifting by n cyclically permutes the blocks,\n # preserving the set of sums.\n for s in range(n):\n block_sums = []\n \n # a. Generate the m blocks for this shift\n # The cut corresponds to blocks starting at indices s, s+n, s+2n, ... (modulo total length)\n for i in range(m):\n start_index = (s + i * n) % total_beads\n \n # b. Calculate the sum (number of 1s) for each of the m blocks.\n current_sum = 0\n for k in range(n):\n idx = (start_index + k) % total_beads\n current_sum += flat_necklace[idx]\n \n block_sums.append(current_sum)\n \n # c. Verify that these m sums are all distinct (i.e., the set of sums has size m).\n if len(set(block_sums)) != m:\n print(f\"Error: Condition failed for shift offset {s}. Block sums are {block_sums}, which are not pairwise distinct.\")\n return\n\n # 7. If all checks pass, the construction is valid.\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify_necklace()"} | |
| {"split": "construction", "source": "USAMO-2022-P6", "category": "Graph Theory", "id": "USAMO-2022-P6-202", "query": "There are $2022$ users on a social network called Mathbook, and some of them are Mathbook-friends. (On Mathbook, friendship is always mutual and permanent.)\\nStarting now, Mathbook will only allow a new friendship to be formed between two users if they have at least two friends in common. What is the minimum number\\nof friendships that must already exist so that every user could eventually become friends with every other user?", "ref_answer": "With $2022$ replaced by $n$, the answer is $\\\\lceil 3/2n \\\\rceil - 2$.", "instruction": "For the specific case $n=202$ (where the users are represented by integers from 1 to 202), provide an explicit construction of the initial friendships that achieves the minimum possible number of friendships.\n\nConstruction requirements:\n- Output a single Python expression that evaluates to a list of 2-tuples of integers.\n- Each tuple `(u, v)` represents a friendship between user `u` and user `v`.\n- The users must be integers from 1 to 202.\n- The number of friendships in your list must be exactly the minimum required for $n=202$.\n- The provided initial friendships must allow every user to eventually become friends with every other user under the rule that a new friendship can be formed if two users have at least two friends in common.\n- The output must be a single, valid Python expression (e.g., using list comprehensions) that can be evaluated directly by `eval()`. Do not include comments, assignments, or any other code.\n- Put ONLY the Python expression inside the construction block.", "ref_construction": "[(1, 2)] + [edge for i in range(2, 102) for edge in ((2, 2*i - 1), (2*i - 1, 2*i), (2*i, 1))]", "verify_code": "import sys\nimport collections\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n\n try:\n # Evaluate the payload. The instruction explicitly allows Python expressions\n # like list comprehensions, so eval() is used.\n edges_raw = eval(payload)\n except Exception as e:\n print(f\"Failed to evaluate input: {e}\")\n return\n\n try:\n edges_list = list(edges_raw)\n except Exception as e:\n print(f\"Output is not an iterable: {e}\")\n return\n\n normalized_edges = set()\n for edge in edges_list:\n if not isinstance(edge, tuple) or len(edge) != 2:\n print(f\"Invalid edge format: {edge}. Must be a 2-tuple.\")\n return\n u, v = edge\n if not (isinstance(u, int) and isinstance(v, int)):\n print(f\"Edge vertices must be integers: {edge}\")\n return\n if not (1 <= u <= 202 and 1 <= v <= 202):\n print(f\"Vertices must be between 1 and 202: {edge}\")\n return\n if u == v:\n print(f\"Self-loops are not allowed: {edge}\")\n return\n # Normalize edge to be undirected\n normalized_edges.add(tuple(sorted((u, v))))\n\n if len(normalized_edges) != 301:\n print(f\"Expected exactly 301 unique friendships, got {len(normalized_edges)}.\")\n return\n\n # Simulate friendship formation\n adj = {i: set() for i in range(1, 203)}\n for u, v in normalized_edges:\n adj[u].add(v)\n adj[v].add(u)\n\n # Precompute common friends for all pairs\n common_friends = {i: {j: 0 for j in range(1, 203)} for i in range(1, 203)}\n for i in range(1, 203):\n for j in range(i + 1, 203):\n c = len(adj[i].intersection(adj[j]))\n common_friends[i][j] = c\n common_friends[j][i] = c\n\n queue = collections.deque()\n in_queue_or_adj = {i: set(adj[i]) for i in range(1, 203)}\n\n # Enqueue all pairs that initially have >= 2 common friends\n for i in range(1, 203):\n for j in range(i + 1, 203):\n if j not in in_queue_or_adj[i] and common_friends[i][j] >= 2:\n queue.append((i, j))\n in_queue_or_adj[i].add(j)\n in_queue_or_adj[j].add(i)\n\n # Process queue to propagate new friendships\n while queue:\n u, v = queue.popleft()\n \n # For every existing neighbor w of u, u acts as a new common friend for w and v\n for w in adj[u]:\n common_friends[w][v] += 1\n common_friends[v][w] += 1\n if v not in in_queue_or_adj[w] and common_friends[w][v] >= 2:\n queue.append((w, v))\n in_queue_or_adj[w].add(v)\n in_queue_or_adj[v].add(w)\n \n # For every existing neighbor w of v, v acts as a new common friend for w and u\n for w in adj[v]:\n common_friends[w][u] += 1\n common_friends[u][w] += 1\n if u not in in_queue_or_adj[w] and common_friends[w][u] >= 2:\n queue.append((w, u))\n in_queue_or_adj[w].add(u)\n in_queue_or_adj[u].add(w)\n \n # Add the validated friendship to the active adjacency list\n adj[u].add(v)\n adj[v].add(u)\n\n # Verify if the graph has become complete\n total_edges = sum(len(neighbors) for neighbors in adj.values()) // 2\n expected_edges = 202 * 201 // 2\n if total_edges != expected_edges:\n print(f\"Graph does not become complete. Final edge count: {total_edges} instead of {expected_edges}.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()", "grading_guidelines": "(Partial) 1. Gave (and correctly justified) a construction achieving at most \\(\\lceil \\tfrac32 n\\rceil-2\\) initial friendships, e.g. for even \\(n\\) an edge \\(ab\\) plus \\(\\frac n2-1\\) disjoint 4-cycles sharing \\(ab\\), and explained how the allowed rule can then generate all remaining edges. 2. Reformulated the process in graph terms (new edge \\(uv\\) can be added once \\(u,v\\) have at least two common neighbors; equivalently one may complete a \\(C_4\\) to a \\(K_4\\)), and made a correct nontrivial structural observation about how the closure operation behaves (e.g. completing one \\(K_4\\) creates two common neighbors \\(a,b\\) that then force edges between vertices from different blocks). 3. Proved a meaningful lower-bound lemma, e.g. established a bound of the form \\(e(G)\\ge c n - O(1)\\) (with some explicit \\(c>1\\)) necessary for eventual completion to \\(K_n\\), or proved the key invariant for cliques \\(K\\) that \\(\\theta(K)\\ge \\frac{3|K|}{2}-2\\) in the base case and at least one nontrivial merge case. (Almost) 1. Presented the full lower-bound strategy via the clique-merging/labeling algorithm (or an equivalent invariant argument), but left a localized gap in the inductive step when multiple cliques merge (e.g. did not fully justify why the merge step is legal under the “two common friends” rule, or omitted one subcase of how \\(\\theta\\) changes). 2. Proved the sharp lower bound \\(e(G)\\ge \\lceil\\tfrac32 n\\rceil-2\\) and gave the sharp construction, but did not handle one parity/boundary case (typically the odd \\(n\\) adjustment with the extra vertex adjacent to \\(a,b\\)), or made a small counting slip that affects only that case. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "ref_solution": "With $2022$ replaced by $n$, the answer is $\\left\\lceil \\frac{3}{2} n \\right\\rceil - 2$.\n\nIn standard graph theory terms: starting from a graph $G$ on $n$ vertices, we are allowed to take any $C_4$ in the graph and complete it to a $K_4$. The problem asks for the minimum number of edges needed so that this operation lets us transform $G$ to $K_n$. \n\nFor even $n$, start with an edge $ab$, and then create $n/2-1$ copies of $C_4$ that use $ab$ as an edge. This can be completed into $K_n$ by first completing the $n/2-1$ copies of $C_4$ into $K_4$. Then, since any two vertices in different copies of $K_4$ share $a$ and $b$ as common friends, we can connect all remaining pairs of vertices, finishing up the $K_n$. The construction for odd $n$ is the same except with one extra vertex $c$ which is connected to both $a$ and $b$. \n\nNotice that additional operations or connections can never hurt. So we will describe a *specific* algorithm that performs operations on the graph until no more operations are possible. This means that if this algorithm terminates with anything other than $G = K_n$, the graph was never completable to $K_n$ to begin with. \n\nThe algorithm uses the following data: it keeps a list $\\mathcal{C}$ of cliques of $G$, and a labeling $\\mathcal{L} \\colon E(G) \\to \\mathcal{C}$ which assigns to every edge one of the cliques that contains it. Initially, $\\mathcal{C}$ consists of one $K_2$ for every edge of $G$, and each edge is labeled in the obvious way. \n\nAt each step, the algorithm arbitrarily takes any $C_4 = abcd$ whose four edges $ab$, $bc$, $cd$, $da$ do not all have the same label. Consider these labels that appear (at least two, and up to four), and let $V$ be the union of all vertices in any of these $2$ to $4$ cliques. Do the following graph operations: connect $ac$ and $bd$, then connect every vertex in $V \\setminus \\{a,b,c,d\\}$ to each of $\\{a,b,c,d\\}$. Finally, complete this to a clique on $V$. \n\nUpdate $\\mathcal{C}$ by merging these $2$ to $4$ cliques into a single clique $K_V$. Update $\\mathcal{L}$ by replacing every edge that was labeled with one of these cliques with the label $K_V$. Also, update every *newly* created edge to have label $K_V$. However, if there were existing edges not labeled with one of the merged cliques, then we do *not* update these. \n\nStop once every $C_4$ has only one label appearing among its edges. When this occurs, no operations are possible at all on the graph. As we remarked, if the graph is going to be completable to $K_n$ at all, then this algorithm must terminate with $\\mathcal{C} = \\{K_n\\}$. We will use this to prove our bound. \n\nWe proceed by induction in the following way. For a clique $K$, let $\\theta(K)$ denote the number of edges of the *original* graph $G$ which are labeled by $K$ (this does *not* include new edges added by the algorithm); hence the problem amounts to estimating how small $\\theta(K_n)$ can be. \n\nAt any point in the operation, if $K$ is a clique in the cover $\\mathcal{C}$, then \n$$ \\theta(K) \\ge \\frac{3 |K|}{2} - 2 $$\nwhere $|K|$ is the number of vertices in $K$. We prove this by induction on the time step of the algorithm. The base case is clear, because initially $K$ is just a single edge of $G$, so $\\theta(K) = 1$ and $|K| = 2$, which satisfies $1 \\ge \\frac{3(2)}{2} - 2 = 1$. The inductive step proceeds by casework based on how the merge occurred."} | |
| {"split": "construction", "source": "USAMO-2021-P3", "category": "Operations and Strategies", "id": "USAMO-2021-P3-81", "query": "Let $n \\\\geq 2$ be an integer. An $n \\\\times n$ board is initially empty. Each minute, you may perform one of three moves: • If there is an L-shaped tromino region of three cells without stones on the board (see figure; rotations not allowed), you may place a stone in each of those cells. • If all cells in a column have a stone, you may remove all stones from that column. • If all cells in a row have a stone, you may remove all stones from that row. For which $n$ is it possible that, after some non-zero number of moves, the board has no stones?", "ref_answer": "The answer is $3 \\\\mid n$", "instruction": "For $n = 81$, provide an explicit sequence of moves to completely empty the board after a non-zero number of moves.\n\nConstruction format requirements:\n- Output a single Python expression that evaluates to a list of moves.\n- Each move should be a tuple of one of the following forms:\n - `(\"place\", r, c)`: Places an L-tromino such that it covers the cells `(r, c)`, `(r-1, c)`, and `(r, c+1)`. (Here `r` is the 0-based row index and `c` is the 0-based column index, $0 \\le r, c < 81$).\n - `(\"row\", r)`: Removes all stones from row `r` (requires row `r` to be completely full).\n - `(\"col\", c)`: Removes all stones from column `c` (requires column `c` to be completely full).\n- The board is $81 \\times 81$, 0-indexed.\n- The sequence must be valid: you can only place an L-tromino if all three of its cells are currently empty, and you can only clear a row/column if it is completely full.\n- After all moves are executed, the board must be completely empty, and the sequence of moves must be non-empty.\n- The output must be a single, valid Python expression (e.g., using list concatenations and comprehensions).\n- Put ONLY the Python expression inside the `<construct>` block, with no formatting, no markdown code blocks, and no explanations.", "ref_construction": "[(\"place\", 3*i+1, 3*j+1) for i in range(27) for j in range(27)] + [(\"place\", 3*i+2, 3*j) for i in range(27) for j in range(27)] + [(\"row\", 3*i+1) for i in range(27)] + [(\"place\", 3*i+1, 3*j) for i in range(27) for j in range(27)] + [(\"col\", 3*j) for j in range(27)] + [(\"col\", 3*j+1) for j in range(27)]", "verify_code": "import sys\n\ndef verify():\n # Read the raw payload from stdin\n raw_payload = sys.stdin.read().strip()\n if not raw_payload:\n print(\"Empty input.\")\n return\n\n # Evaluate the payload as a Python expression\n try:\n moves = eval(raw_payload)\n except Exception as e:\n print(f\"Failed to parse input: {e}\")\n return\n\n # Verify that the parsed object is a non-empty list of tuples\n if not isinstance(moves, list):\n print(\"Input must evaluate to a list.\")\n return\n if len(moves) == 0:\n print(\"The sequence of moves must be non-empty.\")\n return\n\n # Initialize an 81x81 boolean matrix to False (empty board)\n board = [[False for _ in range(81)] for _ in range(81)]\n\n # Iterate through each move in the list\n for idx, move in enumerate(moves):\n if not isinstance(move, tuple):\n print(f\"Move at index {idx} is not a tuple: {move}\")\n return\n if len(move) == 0:\n print(f\"Move at index {idx} is empty.\")\n return\n \n op = move[0]\n if op == \"place\":\n if len(move) != 3:\n print(f\"Move at index {idx} has invalid length for 'place': {move}\")\n return\n _, r, c = move\n if type(r) is not int or type(c) is not int:\n print(f\"Move at index {idx} has non-integer coordinates: {move}\")\n return\n if not (1 <= r < 81 and 0 <= c < 80):\n print(f\"Move at index {idx} has out-of-bounds coordinates for 'place': {move}\")\n return\n if board[r][c] or board[r-1][c] or board[r][c+1]:\n print(f\"Move at index {idx} attempts to place on non-empty cells: {move}\")\n return\n # Place the L-tromino\n board[r][c] = True\n board[r-1][c] = True\n board[r][c+1] = True\n \n elif op == \"row\":\n if len(move) != 2:\n print(f\"Move at index {idx} has invalid length for 'row': {move}\")\n return\n _, r = move\n if type(r) is not int:\n print(f\"Move at index {idx} has non-integer row index: {move}\")\n return\n if not (0 <= r < 81):\n print(f\"Move at index {idx} has out-of-bounds row index: {move}\")\n return\n if not all(board[r][c] for c in range(81)):\n print(f\"Move at index {idx} attempts to clear row {r} which is not completely full.\")\n return\n # Remove all stones from row r\n for c in range(81):\n board[r][c] = False\n \n elif op == \"col\":\n if len(move) != 2:\n print(f\"Move at index {idx} has invalid length for 'col': {move}\")\n return\n _, c = move\n if type(c) is not int:\n print(f\"Move at index {idx} has non-integer column index: {move}\")\n return\n if not (0 <= c < 81):\n print(f\"Move at index {idx} has out-of-bounds column index: {move}\")\n return\n if not all(board[r][c] for r in range(81)):\n print(f\"Move at index {idx} attempts to clear column {c} which is not completely full.\")\n return\n # Remove all stones from column c\n for r in range(81):\n board[r][c] = False\n \n else:\n print(f\"Move at index {idx} has an invalid operation: {move}\")\n return\n\n # After processing all moves, verify that every cell in the board is False\n for r in range(81):\n for c in range(81):\n if board[r][c]:\n print(f\"After all moves, the board is not empty. Cell ({r}, {c}) contains a stone.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()", "grading_guidelines": "(Partial) 1. Established the correct invariant/encoding of a position by a polynomial (or equivalent linear functional) so that placing an L-tromino adds a translate of 1+x+y and clearing a full row/column corresponds to adding a multiple of 1+x+…+x^{n-1} or 1+y+…+y^{n-1}. 2. Proved the key roots-of-unity test: for any n-th roots of unity z1,z2≠1 one must have (1+z1+z2)P(z1,z2)=0, and observed that if 3∤n then 1+z1+z2≠0 for all such z1,z2. 3. Gave a correct explicit move sequence returning to empty for n=3, or clearly reduced the construction for general n divisible by 3 to a tiling/concatenation of a 3×3 gadget. (Almost) 1. Proved the impossibility for 3∤n via the polynomial/roots-of-unity method, but left a minor gap in justifying why existence of a nontrivial return-to-empty sequence yields a nonzero P with deg_x,deg_y≤n−2 in the stated ideal condition. 2. Completed the vanishing-on-S×S argument for 3∤n, but the final contradiction (e.g., the application of Combinatorial Nullstellensatz / degree-counting to deduce P≡0) is insufficiently justified or misses one boundary degree case. 3. Gave a correct construction for all n with 3|n and a correct outline of the converse, but omitted the check that rotations are not allowed in the L-move (or handled only one orientation) while claiming the full result.", "ref_solution": "The answer is $n$ such that $3 \\mid n$.\n\n**Construction for $3 \\mid n$:**\nFor $n=3$, a fairly straightforward sequence of moves exists to return to the empty board. This construction can then be extended to any $n$ such that $3 \\mid n$.\n\n**Polynomial-based proof of converse:**\nAssume for contradiction that $3 \\nmid n$. We will show the task is impossible even if we allow stones to have real weights in our process. \n\nA valid elimination corresponds to a non-zero polynomial $P \\in \\mathbb{R}[x,y]$ such that\n\\begin{align*}\n\\deg_x P &\\le n-2 \\\\\n\\deg_y P &\\le n-2 \\\\\n(1+x+y) P(x,y) &\\in \\left\\langle 1+x+\\dots+x^{n-1}, \\; 1+y+\\dots+y^{n-1}\\right\\rangle.\n\\end{align*}\n(Here $\\langle \\dots \\rangle$ is an ideal of $\\mathbb{R}[x,y]$.) \n\nIn particular, if $S$ is the set of $n$-th roots of unity other than $1$, we should have \n\\[\n(1+z_1+z_2) P( z_1, z_2 ) = 0\n\\]\nfor any $z_1 , z_2 \\in S$. Since $3 \\nmid n$, it follows that $1+z_1+z_2 \\neq 0$ always. So $P$ vanishes on $S \\times S$, a contradiction to the bounds on $\\deg P$ (by, say, the Combinatorial Nullstellensatz on any nonzero term)."} | |
| {"split": "construction", "source": "USAMO-2020-P2", "category": "Extremal Problems", "id": "USAMO-2020-P2", "query": "Consider a hollow cube of dimensions $2020\\\\times2020\\\\times2020$ whose six faces are each divided into $2020\\\\times2020$ unit squares. A solid rectangular block of dimensions $1\\\\times1\\\\times2020$ is called a \\\"brick.\\\" Place several such bricks inside the cube such that: (1) The two $1\\\\times1$ faces of each brick coincide with two unit squares on a pair of opposite faces of the cube (there are $3\\\\times2020^2$ ways to place a brick); (2) Any two bricks have no interior points in common; (3) Each of the four $1\\\\times2020$ faces of every brick either shares interior points with a face of the cube or shares interior points with a $1\\\\times2020$ face of another brick. Find the minimum possible number of bricks placed. Note: The interior points of a brick refer to points not on its faces or edges; the interior points of a face refer to points not on the boundary of the face.", "ref_answer": "3030", "ref_solution": "Let the cube be represented by the region $[0, 2020]^3$ in a Cartesian coordinate system. A brick is a $1 \\times 1 \\times 2020$ rectangular block. Based on its orientation, a brick can be parallel to the $x$, $y$, or $z$ axis. \n\nWe denote an $x$-oriented brick by $(*, b, c)$, representing the region $[0, 2020] \\times [b-1, b] \\times [c-1, c]$ for integers $b, c \\in \\{1, 2, \\dots, 2020\\}$. Here, $b$ and $c$ are its fixed $y$ and $z$ components. Similarly, a $y$-oriented brick is denoted $(a, *, c)$, and a $z$-oriented brick is denoted $(a, b, *)$. \n\nBy condition (3), each of the four $1 \\times 2020$ faces of a brick must share interior points with a face of the cube or a $1 \\times 2020$ face of another brick. For two faces to share 2-dimensional interior points, they must be coplanar. Thus, a face normal to a given axis can only share interior points with another face normal to the same axis.\n\nBelow we prove that at least $3030$ bricks must be placed. We divide the analysis into two cases based on the orientations present.\n\n**Case 1: At least one orientation is entirely missing.**\nWithout loss of generality, assume there are no $z$-oriented bricks, meaning no bricks of the form $(x, y, *)$. Since some bricks must be placed, assume without loss of generality that there is an $x$-oriented brick $(*, b, c)$ on the layer $z=c$. \n\nIts $1 \\times 2020$ faces normal to the $y$-axis (at $y=b-1$ and $y=b$) must be shared with the boundary of the cube or with other bricks. Since there are no $z$-oriented bricks, the only available bricks with faces normal to the $y$-axis are other $x$-oriented bricks. Thus, the brick $(*, b, c)$ can only share its $y$-normal faces with $(*, b-1, c)$ and $(*, b+1, c)$. This forces the entire layer $z=c$ to be completely filled with $x$-oriented bricks $(*, y, c)$ for all $y \\in \\{1, 2, \\dots, 2020\\}$. \n\nFurthermore, the faces of these bricks normal to the $z$-axis (at $z=c-1$ and $z=c$) must be shared with bricks in the adjacent layers. This forces the adjacent layers to contain bricks, and by the same logic, those layers must also be completely filled. Consequently, every layer of the cube must be completely filled, requiring $2020^2 > 3030$ bricks.\n\n**Case 2: All three orientations are present.**\nSuppose bricks of all three orientations appear, for instance $(a, b, *)$, $(*, c, d)$, and $(e, *, f)$. \n\nConsider a brick whose $x$-component is $a$, such as the $z$-oriented brick $(a, b, *)$. Its $1 \\times 2020$ faces normal to the $x$-axis (at $x=a-1$ and $x=a$) must be shared with the cube boundary or with other bricks having faces normal to the $x$-axis. The only bricks with faces normal to the $x$-axis are $z$-oriented bricks $(x, y, *)$ and $y$-oriented bricks $(x, *, z)$, both of which have a specific $x$-component. Therefore, by condition (3), there must be a brick whose $x$-component is $a-1$ and a brick whose $x$-component is $a+1$ (unless $a=1$ or $a=2020$, where the face can be shared with the cube boundary). \n\nBy induction, the $x$-components $1, 2, \\dots, 2020$ must all appear among the placed bricks. Similarly, because $x$-oriented and $y$-oriented bricks are also present, the $y$-components and $z$-components $1, 2, \\dots, 2020$ must all appear among the bricks.\n\nSince each brick accounts for exactly two fixed components, we can bound the total number of bricks. Let $n_x, n_y, n_z$ be the number of $x$-oriented, $y$-oriented, and $z$-oriented bricks, respectively. An $x$-oriented brick provides a $y$ and a $z$ component, a $y$-oriented brick provides an $x$ and a $z$ component, and a $z$-oriented brick provides an $x$ and a $y$ component. The total number of distinct $x$-components present is bounded above by the number of bricks providing an $x$-component, which is $n_y + n_z$. Since all 2020 possible $x$-components must appear, we have:\n$$n_y + n_z \\ge 2020$$\nSimilarly, for the $y$ and $z$ components, we have:\n$$n_x + n_z \\ge 2020$$\n$$n_x + n_y \\ge 2020$$\nSumming these three inequalities yields:\n$$2(n_x + n_y + n_z) \\ge 3 \\times 2020 \\implies n_x + n_y + n_z \\ge 3030.$$\n\nIn both cases, the number of bricks is at least $3030$. Thus, the minimum possible number of bricks placed is $3030$.", "grading_guidelines": "(Partial) 1. Made the key coplanarity observation: for two $1\\times 2020$ faces to share interior points, they must be coplanar, hence a face normal to a given axis can only be supported by the cube boundary or by faces of bricks that are also normal to that axis. 2. In the “missing orientation” case (e.g. no $z$-oriented bricks), showed that an $x$-oriented brick $(*,b,c)$ forces the neighboring bricks $(*,b\\pm1,c)$ (unless on the boundary), and hence forces the entire $z=c$ layer to be filled with $2020$ parallel bricks. 3. In the “all three orientations present” case, proved the propagation lemma that if some $x$-coordinate $a$ occurs as a fixed coordinate of a brick, then (unless $a=1$ or $2020$) some brick must realize $x=a-1$ and some brick must realize $x=a+1$, so by induction all $x$-coordinates $1,2,\\dots,2020$ occur (and similarly for $y$ and $z$). (Almost) 1. Correctly derived that all three coordinate sets $\\{1,2,\\dots,2020\\}$ must appear (in the all-three-orientations case) and set up the inequalities $n_y+n_z\\ge2020$, $n_x+n_z\\ge2020$, $n_x+n_y\\ge2020$, but made an arithmetic slip or did not clearly justify why each distinct coordinate must be contributed by a distinct brick, so the final bound $n_x+n_y+n_z\\ge3030$ is not fully secured. 2. Correctly handled the missing-orientation case and concluded it forces at least $2020^2$ bricks, but did not finish the all-three-orientations case (or omitted a boundary subcase in the propagation argument) needed to obtain the sharp lower bound $3030$. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For the specific case of a $20 \\times 20 \\times 20$ cube (i.e., replacing 2020 with $2n$ where $n=10$), provide an explicit construction of the bricks that minimizes the total number of bricks placed.\n\nConstruction requirements:\n- Output a single Python expression that evaluates to a list of tuples.\n- Each element in the list must represent one brick and be a tuple of two tuples: `((x1, y1, z1), (x2, y2, z2))`, where the two inner tuples are the 1-based coordinates of the two $1 \\times 1$ end-cubes of the brick.\n- For example, a brick spanning the entire x-axis at y=2, z=3 would be `((1, 2, 3), (20, 2, 3))`.\n- The construction must satisfy all adjacency and non-intersection constraints described in the problem.\n- The number of bricks must be the absolute minimum possible for a $20 \\times 20 \\times 20$ cube.\n- Use a single, valid Python expression (e.g., combining list comprehensions). Do not include any assignments, block statements, or non-executable text.\n- Put ONLY the Python expression inside the `<construct>` block.", "ref_construction": "[((2*i - 1, 2*i - 1, 1), (2*i - 1, 2*i - 1, 20)) for i in range(1, 11)] + [((1, 2*i, 2*i - 1), (20, 2*i, 2*i - 1)) for i in range(1, 11)] + [((2*i, 1, 2*i), (2*i, 20, 2*i)) for i in range(1, 11)]", "verify_code": "import sys\n\ndef verify():\n content = sys.stdin.read().strip()\n if not content:\n print(\"Empty input\")\n return\n\n try:\n # Use eval to support list comprehensions as required by the instruction\n data = eval(content)\n except Exception as e:\n print(f\"Failed to evaluate Python expression: {e}\")\n return\n\n if not isinstance(data, list):\n print(\"Construction must be a list\")\n return\n if len(data) != 30:\n print(f\"Expected exactly 30 bricks, got {len(data)}\")\n return\n\n occupied_cells = set()\n bricks = []\n\n # Parse and validate each brick, and check for non-intersection\n for idx, item in enumerate(data):\n if not isinstance(item, tuple) or len(item) != 2:\n print(f\"Brick at index {idx} is not a tuple of two elements\")\n return\n p1, p2 = item\n if not isinstance(p1, tuple) or len(p1) != 3:\n print(f\"Brick at index {idx} endpoint 1 is not a 3-tuple\")\n return\n if not isinstance(p2, tuple) or len(p2) != 3:\n print(f\"Brick at index {idx} endpoint 2 is not a 3-tuple\")\n return\n \n for val in list(p1) + list(p2):\n if not isinstance(val, int) or isinstance(val, bool):\n print(f\"Coordinate {val} in brick {idx} is not an integer\")\n return\n if val < 1 or val > 20:\n print(f\"Coordinate {val} in brick {idx} is out of bounds (must be 1-20)\")\n return\n\n diffs = [abs(p1[i] - p2[i]) for i in range(3)]\n if diffs.count(19) != 1 or diffs.count(0) != 2:\n print(f\"Brick at index {idx} does not span exactly one full axis from 1 to 20\")\n return\n \n axis = diffs.index(19)\n fixed_coords = list(p1)\n \n cells = []\n for i in range(1, 21):\n c = list(fixed_coords)\n c[axis] = i\n cells.append(tuple(c))\n \n bricks.append({\n 'axis': axis,\n 'fixed_coords': fixed_coords,\n 'cells': cells\n })\n\n for c in cells:\n if c in occupied_cells:\n print(f\"Intersection detected at cell {c}\")\n return\n occupied_cells.add(c)\n \n # Check face adjacency constraints\n for idx, brick in enumerate(bricks):\n axis = brick['axis']\n fixed_coords = brick['fixed_coords']\n \n for d in range(3):\n if d == axis:\n continue\n for delta in (-1, 1):\n v = fixed_coords[d]\n adj_v = v + delta\n \n # If the face is on the boundary of the 20x20x20 cube, it is valid\n if adj_v < 1 or adj_v > 20:\n continue\n \n # Otherwise, it must share a 1x1 area with another brick.\n # Since all bricks span the full length, any occupied cell in the adjacent line\n # guarantees a shared 1x1 or 1x20 face segment.\n adjacent_line_occupied = False\n for i in range(1, 21):\n adj_cell = list(fixed_coords)\n adj_cell[axis] = i\n adj_cell[d] = adj_v\n if tuple(adj_cell) in occupied_cells:\n adjacent_line_occupied = True\n break\n \n if not adjacent_line_occupied:\n face_dir = ['x', 'y', 'z'][d]\n print(f\"Brick at index {idx} fails face adjacency on its {face_dir}={adj_v} face\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "USAMO-2020-P4", "category": "Extremal Problems", "id": "USAMO-2020-P4-10", "query": "Suppose that $(a_1, b_1), (a_2, b_2), \\cdots, (a_100, b_100)$ are distinct ordered pairs of nonnegative integers. Let $N$ denote the number of pairs of integers $(i, j)$ satisfying $1 \\leq i < j \\leq 100$ and $|aibj − aj bi| = 1. Determine the largest possible value of Nover all possible choices of the 100 ordered pairs.", "ref_answer": "The answer is $197$. In general, if $100$ is replaced by $n \\geq 2$ the answer is $2n − 3$.", "ref_solution": "The answer is $197$. In general, if $100$ is replaced by $n \\ge 2$, the answer is $2n-3$.\n\nLet $P_i = (a_i, b_i)$ be a point in the coordinate plane, and let $O = (0,0)$. The condition $|a_i b_j - a_j b_i| = 1$ is equivalent to the condition that the area of $\\triangle O P_i P_j$ is exactly $1/2$. We wish to maximize the number of such triangles. Call a triangle with area $1/2$ and one vertex at $O$ *good*.\n\n\\paragraph{Construction of $197$ pairs.}\nIt suffices to use the $100$ points $(1,0)$ and $(k,1)$ for $k=1, 2, \\dots, 99$. Notice that:\n\\begin{itemize}\n\\item There are $98$ good triangles with vertices $(0,0)$, $(k,1)$, and $(k+1,1)$ for $k=1, \\dots, 98$.\n\\item There are $99$ good triangles with vertices $(0,0)$, $(1,0)$, and $(k,1)$ for $k=1, \\dots, 99$.\n\\end{itemize}\nThis yields a total of $98 + 99 = 197$ good triangles.\n\n\\paragraph{Proof that $197$ pairs is optimal.}\nWe proceed by induction on $n$ to show the upper bound of $2n-3$. The base case $n=2$ is evident, yielding at most $2(2)-3 = 1$ good triangle. \n\nFor the inductive step, suppose (without loss of generality) that the point $P = P_n = (a,b)$ is the farthest away from the origin $O$ among all $n$ points.\n\n\\begin{claim*}\nThis farthest point $P = P_n$ is part of at most two good triangles.\n\\end{claim*}\n\n\\begin{proof}\nWe must have $\\gcd(a,b) = 1$ for $P$ to be in any good triangles at all, since otherwise any divisor of $\\gcd(a,b)$ would also divide $2[OPQ] = |a b_Q - b a_Q| = 1$. \n\nConsider the locus of all points $Q$ for which $[OPQ] = 1/2$. This locus consists of two parallel lines passing with slope $OP$. Since $\\gcd(a,b)=1$, the distance between consecutive lattice points on each of these two lines is exactly $\\sqrt{a^2+b^2} = OP$. Indeed, if one of the points is $(u,v)$, then the others on the line are $(u \\pm a, v \\pm b)$ where the signs match.\n\nBecause $P$ is chosen to be the farthest point from $O$ among all given points, any valid point $Q$ must lie inside the quarter-circle in the first quadrant centered at $O$ with radius $OP$. Since the given points have nonnegative coordinates and $P \\neq O$ implies $a,b \\ge 0$ with at least one strictly positive, moving from $(u,v)$ by adding $(a,b)$ strictly increases the distance from the origin. Specifically, $(u+a)^2 + (v+b)^2 = u^2+v^2 + a^2+b^2 + 2(au+bv) \\ge OP^2 + u^2+v^2 > OP^2$. Consequently, only two lattice points on this locus (at most one on each line) actually lie inside the quarter-circle centered at $O$ with radius $OP$. Thus, across both lines, there are at most two valid lattice points $Q$ available among the given points. This proves the claim.\n\\end{proof}\n\nThis claim allows us to complete the induction by simply deleting $P_n$. We lose at most $2$ good triangles, and by the inductive hypothesis, the remaining $n-1$ points form at most $2(n-1)-3$ good triangles. Thus, the $n$ points form at most $2(n-1)-3 + 2 = 2n-3$ good triangles.\n\nFor $n=100$, the maximum number of good triangles is $2(100)-3 = 197$.", "grading_guidelines": "(Partial) 1. Reformulated the condition |a_ib_j-a_jb_i|=1 as: the triangle with vertices O=(0,0), P_i, P_j has area 1/2 (equivalently the vectors form a unimodular pair). 2. Gave a construction producing N=197 (e.g. using (1,0) and (k,1) for k=1,…,99, and correctly counted 99+98 pairs with determinant ±1). 3. Proved a nontrivial upper bound step such as: if P=(a,b) participates in a good pair then gcd(a,b)=1, or described/derived the two parallel lines of integer points Q satisfying |ab_Q-ba_Q|=1. (Almost) 1. Proved the general upper bound N≤2n−3 by deleting a farthest point P and showing it can be in at most two good pairs, but left a localized gap in justifying “at most two” (e.g. incomplete argument about lattice spacing on the locus lines or why only one point per line can lie within the radius OP). 2. Completed the induction and obtained N≤197 for n=100, but did not give (or miscounted slightly) a matching construction attaining 197. 3. Gave the correct construction and the induction framework, but omitted checking a boundary case (e.g. when a=0 or b=0, or when gcd(a,b)>1 implying no good pairs), or made a small determinant/strict-inequality error in the distance comparison for excluding further points on the locus.", "instruction": "For n = 10, construct an array of 10 ordered pairs of nonnegative integers that maximizes the number of pairs (i, j) satisfying 1 <= i < j <= 10 and |a_i * b_j - a_j * b_i| = 1.\n\nRequirements for the construction:\n- Provide exactly 10 distinct ordered pairs.\n- Represent the ordered pairs as a Python list of lists (e.g., [[a1, b1], [a2, b2], ..., [a10, b10]]).\n- Ensure all integers are nonnegative.\n- The construction must achieve the maximum possible value of N for n = 10.\n- Include exactly one construction block and put ONLY the Python literal list between the tags:\n<construct>\n</construct>\n- Do not use code fences. Do not put any extra text inside <construct>...</construct>.", "ref_construction": "[[1, 0], [1, 1], [2, 1], [3, 1], [4, 1], [5, 1], [6, 1], [7, 1], [8, 1], [9, 1]]", "verify_code": "import sys\nimport ast\n\ndef main():\n \"\"\"\n Verifier script for the combinatorics-construction task.\n This script reads a construction of 10 ordered pairs of nonnegative integers\n and verifies that they maximize the number of pairs (i, j) satisfying \n |a_i * b_j - a_j * b_i| = 1.\n \"\"\"\n try:\n # Read the raw input from stdin\n raw_input = sys.stdin.read().strip()\n if not raw_input:\n print(\"Error: No input provided.\")\n return\n \n # Parse the Python literal list\n try:\n data = ast.literal_eval(raw_input)\n except Exception as e:\n print(f\"Error parsing construction: {e}\")\n return\n\n # Verify the structure: a list of exactly 10 elements\n if not isinstance(data, list):\n print(\"Error: The construction must be a list.\")\n return\n \n if len(data) != 10:\n print(f\"Error: Expected exactly 10 pairs, found {len(data)}.\")\n return\n \n pairs = []\n for i, item in enumerate(data):\n # Verify each element is a list or tuple of exactly 2 elements\n if not isinstance(item, (list, tuple)) or len(item) != 2:\n print(f\"Error: Element at index {i} is not a pair (list or tuple of length 2).\")\n return\n \n # Verify each coordinate is an integer (and not a boolean subclass)\n if not all(isinstance(x, int) and not isinstance(x, bool) for x in item):\n print(f\"Error: Element at index {i} contains non-integer values.\")\n return\n \n # Verify all integers are nonnegative\n if not all(x >= 0 for x in item):\n print(f\"Error: Element at index {i} contains negative integers.\")\n return\n \n pairs.append(tuple(item))\n \n # Verify that all 10 pairs are distinct\n if len(set(pairs)) != 10:\n print(\"Error: The 10 pairs are not distinct.\")\n return\n \n # Calculate N: the number of pairs (i, j) with 0 <= i < j < 10 satisfying |a_i*b_j - a_j*b_i| = 1\n n_count = 0\n n = len(pairs)\n for i in range(n):\n for j in range(i + 1, n):\n a_i, b_i = pairs[i]\n a_j, b_j = pairs[j]\n # Calculate the absolute difference of the cross-product\n if abs(a_i * b_j - a_j * b_i) == 1:\n n_count += 1\n \n # The theoretical maximum for n=10 is 2n - 3 = 17\n expected_n = 17\n if n_count == expected_n:\n print(\"True\")\n else:\n print(f\"Error: N_count is {n_count}, but the maximum value for n=10 is {expected_n}.\")\n\n except Exception as e:\n # Catch-all for any unexpected runtime errors\n print(f\"Error: {e}\")\n\nif __name__ == \"__main__\":\n main()"} | |
| {"split": "construction", "source": "USAMO-2009-P3", "category": "Existence and Construction", "id": "USAMO-2009-P3-20-21", "query": "We define a \\emph{chessboard polygon} to be a simple polygon whose sides are\nsituated along lines of the form $x=a$ or $y=b$, where $a$ and $b$ are integers.\nThese lines divide the interior into unit squares, which are shaded alternately\ngray and white so that adjacent squares have different colors.\nTo tile a chessboard polygon by dominoes is to\nexactly cover the polygon by non-overlapping $ 1 \\times 2$ rectangles.\nFinally, a \\emph{tasteful tiling} is one which avoids the\ntwo configurations of dominoes and colors shown on the left below.\n\nProve 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.", "ref_answer": "Proof.", "ref_solution": "\\paragraph{Proof of (a).}\nThis 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:\n\\begin{itemize}\n \\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.\n \\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.\n\\end{itemize}\n\n\\paragraph{Proof of (b).}\nWe 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.\n\nNow 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.", "instruction": "For the specific case of a $20 \\times 21$ rectangular chessboard polygon (20 rows, 21 columns), provide a tasteful tiling by dominoes.\n\nConstruction requirements:\n- Output a single Python expression that evaluates to a list of 20 lists, each of length 21, representing the grid.\n- 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.\n- The grid coloring must follow the standard chessboard pattern with the top-left square (0,0) being White (\"W\").\n- 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.\n- The tiling must be \"tasteful\", meaning it contains none of the following $2 \\times 2$ subgrid configurations (where $k \\neq t$):\n 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).\n 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).\n- 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.\n- Put ONLY the Python expression inside the construction block.", "ref_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)]", "verify_code": "import sys\nimport ast\n\ndef verify():\n try:\n payload = sys.stdin.read().strip()\n except Exception as e:\n print(f\"Error reading input: {e}\")\n return\n\n if not payload:\n print(\"Error: Input is empty.\")\n return\n\n try:\n tree = ast.parse(payload, mode=\"eval\")\n grid = eval(\n compile(tree, \"<construction>\", \"eval\"),\n {\"__builtins__\": {}, \"range\": range, \"enumerate\": enumerate, \"str\": str, \"len\": len},\n {},\n )\n except Exception as e:\n print(f\"Error: Input is not a valid allowed Python expression. {e}\")\n return\n\n rows, cols = 20, 21\n\n if not isinstance(grid, list):\n print(\"Error: Input must evaluate to a list.\")\n return\n if len(grid) != rows:\n print(f\"Error: Grid must have exactly {rows} rows, found {len(grid)}.\")\n return\n\n parsed = [[None for _ in range(cols)] for _ in range(rows)]\n dominoes = {}\n\n for r, row in enumerate(grid):\n if not isinstance(row, list):\n print(f\"Error: Row {r} is not a list.\")\n return\n if len(row) != cols:\n print(f\"Error: Row {r} must have exactly {cols} columns, found {len(row)}.\")\n return\n for c, cell in enumerate(row):\n if not isinstance(cell, str):\n print(f\"Error: Cell ({r}, {c}) is not a string.\")\n return\n parts = cell.split(\"_\")\n if len(parts) != 2:\n print(f\"Error: Cell ({r}, {c}) '{cell}' invalid format. Expected 'Color_ID'.\")\n return\n color, id_text = parts\n expected_color = \"W\" if (r + c) % 2 == 0 else \"B\"\n if color != expected_color:\n print(f\"Error: Cell ({r}, {c}) has color '{color}', expected '{expected_color}'.\")\n return\n if not id_text.isdigit():\n print(f\"Error: Cell ({r}, {c}) ID '{id_text}' is not a positive integer string.\")\n return\n k = int(id_text)\n if k <= 0:\n print(f\"Error: Cell ({r}, {c}) ID {k} must be positive.\")\n return\n parsed[r][c] = {\"color\": color, \"id\": k}\n dominoes.setdefault(k, []).append((r, c))\n\n expected_ids = set(range(1, rows * cols // 2 + 1))\n actual_ids = set(dominoes)\n if actual_ids != expected_ids:\n missing = sorted(expected_ids - actual_ids)\n extra = sorted(actual_ids - expected_ids)\n if missing:\n print(f\"Error: Missing domino IDs, first few: {missing[:10]}.\")\n return\n print(f\"Error: Unexpected domino IDs, first few: {extra[:10]}.\")\n return\n\n for k in range(1, rows * cols // 2 + 1):\n cells = dominoes[k]\n if len(cells) != 2:\n print(f\"Error: Domino ID {k} appears {len(cells)} times. Must appear exactly twice.\")\n return\n (r1, c1), (r2, c2) = cells\n dr = abs(r1 - r2)\n dc = abs(c1 - c2)\n if not ((dr == 1 and dc == 0) or (dr == 0 and dc == 1)):\n print(f\"Error: Domino {k} cells ({r1},{c1}) and ({r2},{c2}) are not edge-adjacent.\")\n return\n if parsed[r1][c1][\"color\"] == parsed[r2][c2][\"color\"]:\n print(f\"Error: Domino {k} does not cover one white and one black square.\")\n return\n\n for r in range(rows - 1):\n for c in range(cols - 1):\n tl = parsed[r][c]\n tr = parsed[r][c + 1]\n bl = parsed[r + 1][c]\n br = parsed[r + 1][c + 1]\n\n if tl[\"color\"] == \"W\":\n if tl[\"id\"] == bl[\"id\"] and tr[\"id\"] == br[\"id\"] and tl[\"id\"] != tr[\"id\"]:\n print(f\"Error: Forbidden vertical pair at 2x2 block with top-left ({r}, {c}).\")\n return\n else:\n if tl[\"id\"] == tr[\"id\"] and bl[\"id\"] == br[\"id\"] and tl[\"id\"] != bl[\"id\"]:\n print(f\"Error: Forbidden horizontal pair at 2x2 block with top-left ({r}, {c}).\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "USAMO-2001-P1", "category": "Extremal Problems", "id": "USAMO-2001-P1", "query": "Each of eight boxes contains six balls. Each ball has been colored with one of $n$ colors, such that no two balls in the same box are the same color, and no two colors occur together in more than one box. Find with proof the smallest possible $n$.", "ref_answer": "The answer is $n = 23$.", "ref_solution": "The answer is $n = 23$. \n\nShown below is a construction using 23 colors, which we denote by $\\{1,2,\\dots,15,a,\\dots,f,X,Y\\}$. The 8 columns represent the 8 boxes, each containing 6 balls:\n\\[\n\\begin{bmatrix}\nX & X & X & 1 & 2 & 3 & 4 & 5 \\\\\n1 & 6 & 11 & 6 & 7 & 8 & 9 & 10 \\\\\n2 & 7 & 12 & 11 & 12 & 13 & 14 & 15 \\\\\n3 & 8 & 13 & Y & Y & Y & a & b \\\\\n4 & 9 & 14 & a & c & e & c & d \\\\\n5 & 10 & 15 & b & d & f & e & f\n\\end{bmatrix}\n\\]\nIt is straightforward to verify that no two balls in the same box have the same color, and any two boxes share at most one color.\n\nWe present two proofs that $n = 23$ is the best possible. The first proof also motivates the construction above. We say a color $x$ is *overrated* if it is used at least three times overall. \n\nFirst, we make the following smoothing argument. Suppose some box $A$ contains a ball of an overrated color $x$ and a ball of color $y$ used only once overall. Then we can change a ball of color $x$ in a different box $B$ to color $y$ while preserving all conditions. (Since $y$ was only in $A$, the only new pairs of balls with the same color are between $A$ and $B$, which previously intersected at $x$.) By applying this operation as many times as possible, we arrive at a configuration where whenever a box contains an overrated color, all other colors in that box are used twice or more overall.\n\nAssume that $n \\le 23$ and that we have applied this smoothing. We will show that $n$ must be exactly 23 and the configuration must be of the form given above. First, observe that no color can be used 4 or more times. If a color $X$ appears in $k$ boxes, then any such box contains 5 other colors. Since $X$ is overrated, our smoothing ensures these 5 colors are used at least twice each, so they must appear at least 5 times in total among the remaining $8 - k$ boxes. However, to avoid two boxes sharing more than one color, these 5 colors can appear at most once in each of the remaining $8 - k$ boxes. Thus, $5 \\le 8 - k$, which implies $k \\le 3$. Therefore, no color is used more than 3 times.\n\nSince there are a total of 48 balls, and each of the $n \\le 23$ colors is used at most 3 times, at least two colors must be overrated (used exactly 3 times). Let $X$ be an overrated color and consider the three boxes where it appears. There are $3 \\times 5 = 15$ other balls in these boxes. Since these three boxes already pairwise intersect at $X$, all 15 of these balls must have distinct colors, say $\\{1, \\dots, 15\\}$. Because $X$ is overrated, the smoothing condition requires that each of these 15 colors must appear at least once more in the remaining 5 boxes. To avoid sharing more than one color with the first three boxes, each of the remaining 5 boxes must contain exactly one color from the first box, one from the second, and one from the third. Thus, we arrive at the following configuration for the first three boxes and the partial configuration for the remaining five (up to a harmless permutation of the colors and boxes):\n\\[\n\\begin{bmatrix}\nX & X & X & 1 & 2 & 3 & 4 & 5 \\\\\n1 & 6 & 11 & 6 & 7 & 8 & 9 & 10 \\\\\n2 & 7 & 12 & 11 & 12 & 13 & 14 & 15 \\\\\n3 & 8 & 13 & & & & & \\\\\n4 & 9 & 14 & & & & & \\\\\n5 & 10 & 15 & & & & & \n\\end{bmatrix}\n\\]\nNow, note that none of these 15 colors can reappear in the remaining slots of the last five boxes, as that would force a box to contain two colors from the same group of 5, creating an intersection of size two with one of the first three boxes. \n\nSo it remains to fill the remaining 15 slots in the last five boxes. We established that there is at least one more overrated color, distinct from any we have seen (since $X$ is used 3 times and $1, \\dots, 15$ are used 2 times each); call it $Y$. Since the first three boxes are full, $Y$ must appear in three of the last five boxes. In the three boxes where $Y$ appears, there are $3 \\times 6 = 18$ total slots. Nine of these slots are filled by colors from $\\{1, \\dots, 15\\}$, and three are filled by $Y$. This leaves $18 - 9 - 3 = 6$ slots. These 6 slots must be filled with completely new colors, and they must all be distinct to avoid creating multiple intersections among the three boxes containing $Y$. This gives a strict lower bound on the total number of colors: $n \\ge 1 \\text{ (for } X) + 15 \\text{ (for } 1 \\dots 15) + 1 \\text{ (for } Y) + 6 \\text{ (new colors)} = 23$. This is exactly the bound we sought, and equality occurs exactly as in our construction.\n\nHere is a short second proof of the bound. Consider the $8 \\times 6$ grid of colors as before. For each ball $b$, let $n_b$ be the total number of times its color is used overall. We assign each ball a weight of $\\frac{1}{n_b}$. Summing these weights over all 48 balls gives exactly the total number of colors $n$:\n\\[\nn = \\sum_{\\text{all } 48 \\text{ balls } b} \\frac{1}{n_b}.\n\\]\nOn the other hand, consider any given box $B$. For each ball $b \\in B$, its color appears in $n_b - 1$ other boxes. Because any two boxes share at most one color, the sets of other boxes containing the colors of the balls in $B$ must be pairwise disjoint. Since there are only 7 other boxes in total, we must have:\n\\[\n\\sum_{b \\in B} (n_b - 1) \\le 7 \\implies \\sum_{b \\in B} n_b \\le 13.\n\\]\nWe want to minimize the sum of the weights $\\sum_{b \\in B} \\frac{1}{n_b}$ in box $B$ subject to the constraints that the $n_b$ are positive integers and $\\sum_{b \\in B} n_b \\le 13$. Since the function $f(x) = \\frac{1}{x}$ is strictly convex, the sum is minimized when the $n_b$ are as large as possible and as nearly equal to each other as possible (a smoothing argument). The optimal integer distribution for a maximum sum of 13 among 6 variables is one 3 and five 2s. Therefore,\n\\[\n\\sum_{b \\in B} \\frac{1}{n_b} \\ge \\frac{1}{3} \\cdot 1 + \\frac{1}{2} \\cdot 5 = \\frac{17}{6}.\n\\]\nSumming this inequality over all 8 boxes yields:\n\\[\nn = \\sum_{\\text{all } 48 \\text{ balls } b} \\frac{1}{n_b} = \\sum_{B} \\sum_{b \\in B} \\frac{1}{n_b} \\ge 8 \\cdot \\frac{17}{6} = \\frac{68}{3} = 22.66\\dots\n\\]\nSince $n$ must be an integer, we conclude that $n \\ge 23$.", "grading_guidelines": "(Partial) 1. Gave a valid construction achieving n=23 (or any explicit construction with n≤23) and checked that no box repeats a color and no pair of boxes shares more than one color. 2. Proved a genuine lower bound n≥23 by a counting/weighting argument, e.g. defining n_b as the multiplicity of a color and showing for each box B that ∑_{b∈B}(n_b−1)≤7 (hence ∑_{b∈B} n_b≤13), then deriving a global bound on n. 3. Established a key structural step from the “overrated color” approach, e.g. proved that no color can occur in 4 or more boxes (hence every color occurs at most 3 times), or carried out the smoothing operation that eliminates a color used once from any box containing a color used ≥3 times. (Almost) 1. Proved n≥23 via the weighting method but left a minor gap in the optimization step (why the minimum of ∑_{b∈B}1/n_b under integer constraints and ∑ n_b≤13 is attained at {3,2,2,2,2,2}), or made a small arithmetic slip after obtaining a bound >22. 2. Completed the overrated-color/smoothing lower-bound strategy up to the final count (identifying one 3-times color X, forcing 15 distinct other colors and their forced second appearances, introducing a second 3-times color Y and concluding 6 new colors), but omitted/blurred one localized justification (e.g. why the 15 colors cannot reappear in the remaining slots of the last five boxes). 3. Produced both the lower bound n≥23 and a construction with 23 colors, but the verification of the construction has a small unchecked intersection case or a minor bookkeeping error; the intended configuration clearly satisfies the conditions.", "instruction": "Find the smallest possible $n$ and provide a construction of the boxes and balls for this $n$. Represent the arrangement as a $6 \\times 8$ matrix where each column corresponds to one of the eight boxes and each row corresponds to one of the six balls in that box. Use integers $1, \\dots, n$ to represent different colors.\n\nRequirements for the construction:\n- The matrix must have exactly 6 rows and 8 columns.\n- Each column must contain 6 distinct integers.\n- For any two distinct columns, the intersection of their sets of integers must contain at most one element.\n- The total number of unique integers $n$ must be the minimum possible.\n- Include exactly one construction block and put ONLY the Python literal matrix between the tags:\n<construct>\n</construct>\n- Do not use code fences. Do not put any extra text inside <construct>...</construct>.", "ref_construction": "[[16, 16, 16, 1, 2, 3, 4, 5], [1, 6, 11, 6, 7, 8, 9, 10], [2, 7, 12, 11, 12, 13, 14, 15], [3, 8, 13, 17, 17, 17, 18, 19], [4, 9, 14, 18, 20, 22, 20, 21], [5, 10, 15, 19, 21, 23, 22, 23]]", "verify_code": "import sys\nimport ast\n\ndef verify():\n try:\n # Read the raw input from stdin\n input_data = sys.stdin.read().strip()\n if not input_data:\n print(\"Error: No input provided.\")\n return\n\n # Parse the input as a Python literal\n try:\n # ast.literal_eval is used to safely evaluate the Python literal matrix\n matrix = ast.literal_eval(input_data)\n except Exception as e:\n print(f\"Error: Failed to parse construction: {e}\")\n return\n\n # Check if the parsed object is a 2D list\n if not isinstance(matrix, list) or not all(isinstance(row, list) for row in matrix):\n print(\"Error: Construction must be a 2D list.\")\n return\n\n # Check dimensions: 6 rows and 8 columns as per instructions\n if len(matrix) != 6:\n print(f\"Error: Matrix must have exactly 6 rows, but has {len(matrix)}.\")\n return\n for i, row in enumerate(matrix):\n if len(row) != 8:\n print(f\"Error: Row {i} must have exactly 8 columns, but has {len(row)}.\")\n return\n\n # Each column represents a box. Transpose the matrix to get the boxes.\n boxes = []\n for c in range(8):\n box = [matrix[r][c] for r in range(6)]\n boxes.append(box)\n\n # 1. Verify that each box (column) contains 6 distinct integers.\n for c, box in enumerate(boxes):\n if len(set(box)) != 6:\n print(f\"Error: Column {c} (box) contains duplicate colors or fewer than 6 elements.\")\n return\n for color in box:\n if not isinstance(color, int):\n print(f\"Error: Color {color} in column {c} is not an integer.\")\n return\n\n # 2. Verify that no two colors occur together in more than one box.\n # This is equivalent to checking that any two distinct columns share at most one color.\n for i in range(8):\n for j in range(i + 1, 8):\n intersection = set(boxes[i]) & set(boxes[j])\n if len(intersection) > 1:\n print(f\"Error: Columns {i} and {j} share {len(intersection)} colors: {intersection}.\")\n return\n\n # 3. Identify all unique colors used in the matrix.\n all_colors = set()\n for box in boxes:\n all_colors.update(box)\n \n # Verify that the total number of unique integers n is 23 (the minimum possible).\n if len(all_colors) != 23:\n print(f\"Error: Total number of unique colors is {len(all_colors)}, but 23 is required.\")\n return\n\n # 4. Verify that the colors used are exactly the integers 1, ..., 23.\n if all_colors != set(range(1, 24)):\n print(f\"Error: Colors must be exactly the integers from 1 to 23.\")\n return\n\n # If all structural and mathematical constraints are satisfied\n print(\"True\")\n\n except Exception as e:\n # Catch any unexpected errors during the verification process\n print(f\"Error: An unexpected error occurred: {e}\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "USAMO-2000-P4", "category": "Extremal Problems", "id": "USAMO-2000-P4", "query": "Find the smallest positive integer $n$ such that if $n$ squares of a $m \\\\times m$ chessboard are colored, then there will exist three colored squares whose centers form a right triangle with sides parallel to the edges of the board.", "ref_answer": "The answer is $n = 2m - 1$.", "instruction": "For the specific case $m=1000$, determine the maximum number of squares that can be colored without creating any three colored squares whose centers form a right triangle with sides parallel to the edges of the board. Provide an explicit construction for this maximum case.\n\nConstruction format requirements:\n- Output a single Python expression (e.g., a list comprehension) that evaluates to a $1000 \\times 1000$ 2D list of integers.\n- The list represents the chessboard, where 1 indicates a colored square and 0 indicates an uncolored square.\n- The construction must strictly avoid any three 1s forming a right triangle with sides parallel to the edges.\n- The total number of colored squares (1s) must be exactly the maximum possible for a $1000 \\times 1000$ board without violating the right triangle constraint.\n- The output must be a pure Python literal/expression that can be directly evaluated by `eval()`. Do not include explanations, comments, print statements, assignments, or any non-expression content.\n\nOutput formatting requirements:\n- Include exactly one construction block and put ONLY the Python expression between the tags:\n<construct>\n</construct>\n- Do not use markdown code fences (like ```python). Do not put any extra text inside <construct>...</construct>.", "ref_construction": "[[1 if (i == 0 or j == 0) and (i != j) else 0 for j in range(1000)] for i in range(1000)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n \n try:\n # Use eval as per instruction to allow list comprehensions\n grid = eval(payload)\n except Exception as e:\n print(f\"Failed to evaluate input: {e}\")\n return\n \n # Verify the parsed object is a list\n if not isinstance(grid, list):\n print(f\"Expected a list, got {type(grid).__name__}.\")\n return\n \n # Verify exactly 1000 rows\n if len(grid) != 1000:\n print(f\"Expected exactly 1000 rows, got {len(grid)}.\")\n return\n \n # Verify each row is a list of exactly 1000 integers (0 or 1)\n for i, row in enumerate(grid):\n if not isinstance(row, list):\n print(f\"Row {i} is not a list.\")\n return\n if len(row) != 1000:\n print(f\"Row {i} does not have exactly 1000 elements (has {len(row)}).\")\n return\n for j, val in enumerate(row):\n if val not in (0, 1):\n print(f\"Element at ({i}, {j}) is not 0 or 1 (got {repr(val)}).\")\n return\n \n # Precompute the sum of 1s in each row and each column\n row_sums = [sum(row) for row in grid]\n col_sums = [sum(grid[r][c] for r in range(1000)) for c in range(1000)]\n \n # Verify the total number of colored squares is exactly 1998\n total_colored = sum(row_sums)\n if total_colored != 1998:\n print(f\"Total number of colored squares must be exactly 1998, but got {total_colored}.\")\n return\n \n # Verify no right triangles with sides parallel to the edges exist\n for r in range(1000):\n for c in range(1000):\n if grid[r][c] == 1:\n if row_sums[r] > 1 and col_sums[c] > 1:\n print(f\"Forbidden right triangle right-angle vertex found at ({r}, {c}). \"\n f\"Row {r} has {row_sums[r]} ones, Column {c} has {col_sums[c]} ones.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()", "grading_guidelines": "(Partial) 1. Gave the extremal construction with 2m-2 colored squares (e.g. a “punctured L”: all squares in one column and one row except the corner), and correctly argued it contains no such right triangle. 2. Made the key observation that a forbidden right triangle is equivalent to: there exist two colored squares in the same column and a third colored square in the same row as one of them but in a different column (or the symmetric statement with rows/columns swapped). 3. Set up a valid counting reduction along the intended lines: classify columns with exactly one colored square versus columns with at least two, and derive a nontrivial bound relating the total number of colored squares to the number of rows that can contain “blocked” positions (even if the final inequality is not completed). (Almost) 1. Proved the upper bound n<=2m-2 for configurations with no right triangle using the row/column blocking (\"death ray\") idea, but left a small gap in justifying why the number of rays/blocked rows is at most m-1 (or made an off-by-one slip that affects only the final constant). 2. Gave both the construction for 2m-2 and a near-complete proof that 2m-1 forces a right triangle, but omitted a boundary case (e.g. handling n<=m separately, or the step that ensures existence of a column with >=2 colored squares when n>m). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "ref_solution": "The answer is $n = 2m - 1$. We present the proof for a $1000 \\times 1000$ board, for which $n = 1999$. \n\nFor a construction with $n = 1998$, take a punctured L as illustrated below (with $1000$ replaced by $4$):\n\\[\n\\begin{bmatrix}\n1 \\\\ \n1 \\\\ \n1 \\\\ \n& 1 & 1 & 1\n\\end{bmatrix}.\n\\]\n\nWe now show that if there is no right triangle, there are at most $1998$ tokens (colored squares). In every column with more than one token, we have each token emit a bidirectional horizontal death ray (laser) covering its entire row: the hypothesis is that the death ray won't hit any other tokens.\n\nAssume there are $n$ tokens and that $n > 1000$. Then obviously some column has more than one token, so at most $999$ tokens don't emit a death ray (namely, any token that is the only token in its column). Thus there are at least $n-999$ death rays. On the other hand, we can have at most $999$ death rays total (since it would not be okay for the whole board to have death rays, as some row should have more than one token, which contradicts the death ray property). Therefore, $n \\le 999 + 999 = 1998$ as desired.\n\nBy replacing $1000$ with $m$, the exact same argument shows that $n \\le 2m - 2$ when no right triangle is formed, so $n = 2m - 1$ is the minimum number of tokens required."} | |
| {"split": "construction", "source": "TSTST-2024-P9", "category": "Extremal Problems", "id": "TSTST-2024-P9-20", "query": "\"Let $n \\ge 2$ be a fixed integer. The cells of an $n \\times n$ table are\nfilled with the integers from $1$ to $n^2$ with each number appearing exactly once.\nLet $N$ be the number of unordered quadruples of cells on this board\nwhich form an axis-aligned rectangle,\nwith the two smaller integers being on opposite vertices of this rectangle.\nFind the largest possible value of $N$.\"", "ref_answer": "(n^4-n^2)/12", "ref_solution": "The largest possible value of $N$ is $\\frac{n^2(n^2-1)}{12}$. \n\nLet 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.\n\n**Proof of the upper bound:**\nCall 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. \n\nObserve 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.\n\n**Claim.** Every axis-aligned rectangle has at least $1$ elbow.\n*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. \n\nLet $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\n\\[\nE \\ge M + 2N = \\binom{n}{2}^2 + N \\iff N \\le E - \\binom{n}{2}^2.\n\\]\n\nTo bound $N$, we provide an upper bound on $E$. For each cell $c$, define:\n- $f(c)$ to be the number of cells in the same row as $c$ which contain a smaller integer than $c$,\n- $g(c)$ to be the number of cells in the same column as $c$ which contain a smaller integer than $c$.\n\nThe number of elbows centered at $c$ is exactly $f(c)g(c)$. Thus, the total number of elbows satisfies\n\\[\nE = \\sum_c f(c)g(c) \\le \\sum_c \\frac{1}{2}\\bigl[f(c)^2+g(c)^2\\bigr].\n\\]\nIn 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,\n\\[\n\\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}.\n\\]\nIt follows that the number of wobbly rectangles satisfies\n\\begin{align*}\nN &\\le E - \\binom{n}{2}^2 \\\\\n&\\le \\frac{n^2(n-1)(2n-1)}{6} - \\frac{n^2(n-1)^2}{4} \\\\\n&= \\frac{n^2(n-1) [2(2n-1) - 3(n-1)]}{12} \\\\\n&= \\frac{n^2(n-1)(n+1)}{12} \\\\\n&= \\frac{n^2(n^2-1)}{12}\n\\end{align*}\nas desired.\n\n**Construction:**\nFrom the proof above, equality holds if and only if $f(c)=g(c)$ everywhere.\n\nSelect 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.", "instruction": "For the specific case $n=20$, provide an explicit construction of the $20 \\times 20$ table that maximizes $N$.\n\nConstruction requirements:\n- Output a single Python expression (a list of lists of integers) representing the $20 \\times 20$ table.\n- The table must contain every integer from 1 to 400 exactly once.\n- 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.\n- The construction must be a single, standalone Python expression that can be directly evaluated using `eval()`.\n- Do not include explanations, comments, markdown code blocks, print statements, assignments, function definitions, imports, classes, asserts, or block `for` statements.\n- Prefer using list comprehensions, conditional expressions, and integer constants to generate a regular, compact, and reproducible expression.\n- Put ONLY the Python expression inside the `<construct>...</construct>` tags.", "ref_construction": "[[((j - i) % 20) * 20 + i + 1 for j in range(20)] for i in range(20)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Error: Empty input.\")\n return\n\n try:\n # Evaluate the payload as a Python expression (supports list comprehensions)\n table = eval(payload)\n except Exception as e:\n print(f\"Parse error: {e}\")\n return\n\n # Check that the parsed object is a list of exactly 20 lists\n if not isinstance(table, list):\n print(\"Error: The evaluated payload is not a list.\")\n return\n \n if len(table) != 20:\n print(f\"Error: Expected exactly 20 rows, got {len(table)}.\")\n return\n \n for i, row in enumerate(table):\n if not isinstance(row, list):\n print(f\"Error: Row {i} is not a list.\")\n return\n if len(row) != 20:\n print(f\"Error: Row {i} does not have exactly 20 elements (has {len(row)}).\")\n return\n for j, val in enumerate(row):\n if type(val) is not int:\n print(f\"Error: Element at row {i}, col {j} is not an integer.\")\n return\n\n # Flatten the matrix and verify it contains all integers from 1 to 400 exactly once\n flattened = [val for row in table for val in row]\n expected_elements = list(range(1, 401))\n if sorted(flattened) != expected_elements:\n print(\"Error: The table does not contain every integer from 1 to 400 exactly once.\")\n return\n\n # Initialize counter N\n N = 0\n \n # Iterate over all pairs of rows r1 < r2 and all pairs of columns c1 < c2\n for r1 in range(20):\n for r2 in range(r1 + 1, 20):\n for c1 in range(20):\n for c2 in range(c1 + 1, 20):\n # Extract the four corner values\n v1 = table[r1][c1]\n v2 = table[r1][c2]\n v3 = table[r2][c1]\n v4 = table[r2][c2]\n \n corners = [\n (v1, r1, c1),\n (v2, r1, c2),\n (v3, r2, c1),\n (v4, r2, c2)\n ]\n \n # Sort the four values to find the two smallest integers\n corners.sort(key=lambda x: x[0])\n \n s1 = corners[0]\n s2 = corners[1]\n \n # Check if the two smallest integers are diagonally opposite\n # (i.e., they do not share the same row and do not share the same column)\n if s1[1] != s2[1] and s1[2] != s2[2]:\n N += 1\n \n # Assert that N is exactly 13,300\n if N != 13300:\n print(f\"Error: The number of valid rectangles N is {N}, but expected exactly 13300.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "TSTST-2023-P7", "category": "Operations and Strategies", "id": "TSTST-2023-P7", "query": "\"The Bank of Pittsburgh issues coins that have a heads side and a tails side.\nVera has a row of $2023$ such coins alternately tails-up and heads-up,\nwith the leftmost coin tails-up.\n\nIn a \\emph{move}, Vera may flip over one of the coins in the row,\nsubject to the following rules:\n\\begin{itemize}\n \\item On the first move, Vera may flip over any of the $2023$ coins.\n \\item On all subsequent moves, Vera may only flip over\n a coin adjacent to the coin she flipped on the previous move.\n (We do not consider a coin to be adjacent to itself.)\n\\end{itemize}\nDetermine the smallest possible number of moves Vera can\nmake to reach a state in which every coin is heads-up.\"", "ref_answer": "4044", "ref_solution": "The answer is $4044$. In general, replacing $2023$ with $4n+3$, the answer is $8n+4$. For $2023$, we have $n = 505$, so the minimum number of moves is $8(505) + 4 = 4044$.\n\n**Lower Bound:**\nLet the coins be indexed $1, 2, \\ldots, 4n+3$ from left to right. The initial state alternates between tails-up and heads-up, starting with tails-up. Thus, the $2n+2$ odd-indexed coins start tails-up, and the $2n+1$ even-indexed coins start heads-up. \n\nBecause Vera may only flip a coin adjacent to the previously flipped coin, her sequence of moves forms a connected walk on the path graph of the coins. Observe that the first coin (index $1$) and the last coin (index $4n+3$) both start tails-up, so they must be flipped at least once. Since the sequence of moves is a connected walk that visits both endpoints of the path, it must visit every coin at least once.\n\nEvery even-indexed coin starts heads-up and must end heads-up, so it must be flipped an even number of times. Since every coin is flipped at least once, each of the $2n+1$ even-indexed coins must be flipped at least twice. Therefore, the total number of flips of even-indexed coins, denoted $E$, satisfies $E \\ge 2(2n+1) = 4n+2$.\n\nLet $O$ be the total number of flips of odd-indexed coins. Because adjacent coins have different parities, the walk strictly alternates between odd-indexed and even-indexed coins. Consequently, the total number of visits to odd and even indices can differ by at most $1$, meaning $|O - E| \\le 1$. Since $E \\ge 4n+2$, it follows that $O \\ge 4n+1$.\n\nEvery odd-indexed coin starts tails-up and must end heads-up, so it must be flipped an odd number of times. The total number of odd flips $O$ is the sum of the flip counts of the $2n+2$ odd-indexed coins. Since $2n+2$ is an even number, $O$ is the sum of an even number of odd integers, which means $O$ must be even. Given that $O \\ge 4n+1$ and $O$ is even, we must actually have $O \\ge 4n+2$.\n\nTherefore, the total number of flips is $O + E \\ge (4n+2) + (4n+2) = 8n+4$. For $n=505$, this gives a minimum of $4044$ flips.\n\n**Construction:**\nWe provide a valid sequence of $8n+4$ flips that achieves the goal. \nFor $k=0,1,\\dots,n-1$, Vera flips the following sequence of $8$ coins in order:\n\\[ 4k+1, 4k+2, 4k+3, 4k+2, 4k+3, 4k+4, 4k+3, 4k+4 \\]\nThen, at the end, she flips the final $4$ coins:\n\\[ 4n+1, 4n+2, 4n+3, 4n+2 \\]\n\nTo verify this is a valid sequence of moves, note that within each chunk, consecutive coins are adjacent. Furthermore, the last coin of the chunk for $k$ is $4k+4$, which is adjacent to the first coin of the chunk for $k+1$, $4k+5$. The last coin of the $(n-1)$-th chunk is $4n$, which is adjacent to the first coin of the final sequence, $4n+1$. Thus, the entire sequence forms a valid walk.\n\nFinally, we count the number of times each coin is flipped:\n- In the $k$-th chunk ($0 \\le k \\le n-1$), coin $4k+1$ is flipped $1$ time (odd), coin $4k+2$ is flipped $2$ times (even), coin $4k+3$ is flipped $3$ times (odd), and coin $4k+4$ is flipped $2$ times (even).\n- In the final sequence, coin $4n+1$ is flipped $1$ time (odd), coin $4n+2$ is flipped $2$ times (even), and coin $4n+3$ is flipped $1$ time (odd).\n\nEvery odd-indexed coin is flipped an odd number of times (either $1$ or $3$), so it ends heads-up. Every even-indexed coin is flipped an even number of times (exactly $2$), so it ends heads-up. The total number of flips is $8n+4 = 4044$, as desired.", "grading_guidelines": "(Partial) 1. Observed that any valid move sequence is a walk on the path graph (each move goes to an adjacent coin), hence the parity of the index alternates at every step and the numbers of odd- and even-index flips differ by at most 1 (i.e. |O−E|≤1). 2. Proved that both endpoints must be flipped (since they start tails), hence the walk must visit every vertex at least once (so every coin is flipped at least once). 3. Used initial/final states to derive parity constraints: each even-index coin starts and ends heads so must be flipped an even number of times (hence at least twice), and/or each odd-index coin starts tails so must be flipped an odd number of times. (Almost) 1. Established the lower bound 4044 (or in general 8n+4 for 4n+3 coins) using endpoint-visit implies all visited, even coins need ≥2 flips, |O−E|≤1, and the extra parity correction forcing O to be even, but did not give a construction achieving it. 2. Gave the intended block-walk construction (the repeating 8-move pattern plus the final 4 moves) and argued adjacency/flip-parities correctly for most coins, but made a localized indexing/endpoint mistake (e.g. at the transition between blocks or in the last 4 coins) that prevents full verification. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Provide an explicit construction for the sequence of coins Vera flips to achieve this in the minimum number of moves.\n\nConstruction requirements:\n- Output a single Python list of integers representing the 1-based indices of the coins flipped in order.\n- The list must have the minimum possible length for the 2023 coins.\n- Each integer must be between 1 and 2023 inclusive.\n- The absolute difference between any two adjacent elements in the list must be exactly 1.\n- The sequence of flips must result in all 2023 coins being heads-up (i.e., odd-indexed coins are flipped an odd number of times, and even-indexed coins are flipped an even number of times).\n- Put ONLY the Python list expression inside the `<construct>...</construct>` block. You may use a list comprehension to make it compact. Do not use markdown code fences or add any extra text.", "ref_construction": "[4 * k + d for k in range(505) for d in (1, 2, 3, 2, 3, 4, 3, 4)] + [2021, 2022, 2023, 2022]", "verify_code": "import sys\nfrom collections import Counter\n\ndef verify():\n text = sys.stdin.read().strip()\n if not text:\n print(\"Empty input.\")\n return\n\n try:\n # Evaluate the construction string. We use eval() because the instruction \n # explicitly allows list comprehensions, which ast.literal_eval does not support.\n seq = eval(text)\n except Exception as e:\n print(f\"Parse error: {e}\")\n return\n\n if not isinstance(seq, list):\n print(\"Output must be a single Python list.\")\n return\n \n if len(seq) != 4044:\n print(f\"Expected list of length 4044, but got {len(seq)}.\")\n return\n \n for i, coin in enumerate(seq):\n if not isinstance(coin, int):\n print(f\"Element at index {i} is not an integer: {coin}\")\n return\n if not (1 <= coin <= 2023):\n print(f\"Coin index out of range at position {i}: {coin}\")\n return\n \n for i in range(len(seq) - 1):\n if abs(seq[i] - seq[i+1]) != 1:\n print(f\"Adjacent elements at indices {i} and {i+1} do not have an absolute difference of 1: {seq[i]} and {seq[i+1]}\")\n return\n \n counts = Counter(seq)\n \n for i in range(1, 2024):\n expected_parity = i % 2\n actual_parity = counts[i] % 2\n if expected_parity != actual_parity:\n print(f\"Coin {i} has incorrect flip parity. Expected {expected_parity}, got {actual_parity} (flipped {counts[i]} times).\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "CTST-2022-P7", "category": "Existence and Construction", "id": "CTST-2022-P7-518", "query": "Find all positive integers $(m,n)$ such that in a grid table formed by $m+1$ horizontal lines and $11$ vertical lines, it is possible to add a diagonal to some of the unit squares (it is allowed to add none, but not allowed to add two in one square), satisfying the condition that the entire figure can be drawn in one stroke and return to the starting point.", "ref_answer": "m=n", "instruction": "For the specific case of a $518 \\times 518$ grid of squares (i.e., $518$ rows and $518$ columns of unit squares), provide an explicit construction of the added diagonals such that every vertex in the resulting graph has an even degree, allowing an Eulerian circuit.\n\nConstruction requirements:\n- Output a single Python expression (e.g., a list comprehension) that evaluates to a list of diagonals.\n- Each diagonal must be represented as a list of two vertices: `[[r1, c1], [r2, c2]]`.\n- Use 0-based coordinates, where `r` is the row index (0 to 518) and `c` is the column index (0 to 518).\n- The top-left vertex of the grid is `[0, 0]` and the bottom-right is `[518, 518]`.\n- A diagonal in the square at row `i` and column `j` (where 0 <= i, j <= 517) must connect either `[i, j]` to `[i+1, j+1]` or `[i+1, j]` to `[i, j+1]`.\n- The expression must not contain assignments, loops (other than in comprehensions), or any non-expression content.\n- Put ONLY the Python expression inside the construction block.", "ref_construction": "[[[i, j], [i + 1, j + 1]] for i in range(518) for j in range(518) if i != j]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n\n try:\n # Evaluate using eval() to support list comprehensions as requested\n diagonals = eval(payload)\n except Exception as e:\n print(f\"Failed to evaluate input: {e}\")\n return\n\n if not isinstance(diagonals, list):\n print(\"Evaluated result is not a list.\")\n return\n\n squares_used = set()\n N = 518\n \n # Initialize degrees for all vertices in the (N+1) x (N+1) grid\n degrees = {}\n for r in range(N + 1):\n for c in range(N + 1):\n if (r == 0 or r == N) and (c == 0 or c == N):\n degrees[(r, c)] = 2\n elif r == 0 or r == N or c == 0 or c == N:\n degrees[(r, c)] = 3\n else:\n degrees[(r, c)] = 4\n\n # Process each diagonal\n for idx, diag in enumerate(diagonals):\n if not isinstance(diag, list) or len(diag) != 2:\n print(f\"Diagonal at index {idx} is not a list of two vertices: {diag}\")\n return\n \n v1, v2 = diag\n if not isinstance(v1, list) or len(v1) != 2 or not isinstance(v2, list) or len(v2) != 2:\n print(f\"Vertices of diagonal at index {idx} are not valid lists of length 2: {diag}\")\n return\n \n r1, c1 = v1\n r2, c2 = v2\n \n if type(r1) is not int or type(c1) is not int or type(r2) is not int or type(c2) is not int:\n print(f\"Coordinates of diagonal at index {idx} must be integers: {diag}\")\n return\n\n # Determine the square (i, j) this diagonal belongs to\n i = min(r1, r2)\n j = min(c1, c2)\n \n if not (0 <= i < N and 0 <= j < N):\n print(f\"Diagonal at index {idx} is out of bounds for a {N}x{N} grid of squares: {diag}\")\n return\n \n # Check if it's a valid diagonal for square (i, j)\n set1 = {(i, j), (i + 1, j + 1)}\n set2 = {(i + 1, j), (i, j + 1)}\n endpoints = {(r1, c1), (r2, c2)}\n \n if endpoints != set1 and endpoints != set2:\n print(f\"Diagonal at index {idx} is not a valid diagonal for square ({i}, {j}): {diag}\")\n return\n \n # Check for multiple diagonals in the same square\n if (i, j) in squares_used:\n print(f\"Multiple diagonals placed in square ({i}, {j}).\")\n return\n \n squares_used.add((i, j))\n \n # Increment degree for both endpoints\n degrees[(r1, c1)] += 1\n degrees[(r2, c2)] += 1\n\n # Verify that all vertices have an even degree\n for (r, c), deg in degrees.items():\n if deg % 2 != 0:\n print(f\"Vertex ({r}, {c}) has an odd degree: {deg}.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()", "grading_guidelines": "(Partial) 1. Reformulated the condition as an Eulerian circuit problem: the drawing is possible iff every vertex of the resulting planar graph has even degree (connectedness addressed or assumed). 2. Constructed a valid configuration for the case m=10 (i.e. a 10×10 grid): e.g. add the same-direction diagonal in all unit squares except those on the main diagonal, and checked that all vertices have even degree. 3. From the parity constraints at vertices, deduced basic structural facts about the set of added diagonals: corners cannot be incident to added diagonals; each non-corner boundary vertex must be incident to exactly one added diagonal; each interior vertex must be incident to an even number of added diagonals. (Almost) 1. Proved the necessity m=10 (equivalently m=n with n=10) via the standard decomposition of diagonals into disjoint cycles and nonintersecting boundary-to-boundary broken lines, but left one key step insufficiently justified (e.g. why a broken line cannot connect two boundary vertices on the same/opposite side). 2. Completed the parity/coloring and planar-separation argument forcing m=n and hence m=10, but did not explicitly provide (or fully verify) a construction for m=10. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "ref_solution": "Let the grid be of size $m \\times n$. Since there are $11$ vertical lines, the number of columns is $n = 10$.\n\nWhen $m=n$, add a diagonal from the upper left to the lower right in every small square except those on the main diagonal from the upper left to the lower right. In this case, each vertex has even degree, so the entire graph can be drawn in a single stroke and return to the starting point.\n\nConsider only the added diagonals. Because after adding the diagonals each vertex has even degree and the added diagonals do not intersect at interior points, we have: at the four corner vertices of the grid no diagonal is added; at boundary vertices that are not corners exactly one diagonal is added; at interior vertices an even number of diagonals is added. If four diagonals meet at the same interior vertex, they can be split into two non-intersecting broken lines. Thus the whole set of added diagonals consists of some pairwise disjoint cycles and broken lines that connect non-corner boundary vertices of the grid. \n\nColor the vertices alternately black and white; then each such broken line passes through vertices of only one color. These broken lines cannot connect two vertices on the same side of the grid, for otherwise the segment between those two vertices would contain an odd number of vertices on that side, making it impossible to pairwise connect the vertices by non-intersecting broken lines. They also cannot connect two vertices on opposite sides: suppose the two vertices lie on the top and bottom sides; then the broken line would separate the grid into a left part and a right part. The left part would contain an odd number of vertices on the boundary; after removing the two corner vertices the number remains odd, and these odd vertices cannot be paired by non-intersecting broken lines. \n\nHence non-corner vertices on the top and bottom sides can only be connected to non-corner vertices on the left and right sides. Consequently, we have $m=n$. \n\nSince $n = 10$, we conclude that $m = 10$, and the required pair is $(10, 10)$."} | |
| {"split": "construction", "source": "CTST-2018-P20", "category": "Extremal Problems", "id": "CTST-2018-P20", "query": "A class has $32$ students. There are $10$ interest groups in the class, and each interest group has exactly $16$ students from the class. For any two students, the square of the number of interest groups in which exactly one of them participates is called the interest difference of the two students. Let $S$ be the sum of the interest differences over all $\\\\binom{32}{2}$ pairs of students. Find the smallest possible value of $S$.", "ref_answer": "The answer is $14080$.", "ref_solution": "First, we restate the problem in terms of sets. Let $A_1, A_2, \\dots, A_{10}$ be $16$-element subsets of the set $\\{1, 2, \\dots, 32\\}$. \nFor $1 \\le i \\le 32$, denote \n\\[\nD_i = \\{k \\in \\{1, 2, \\dots, 10\\} \\mid i \\in A_k\\}.\n\\] \nWe want to find the minimum possible value of \n\\[\nS = \\sum_{1 \\le i < j \\le 32} \\bigl|D_i \\triangle D_j\\bigr|^2.\n\\] \n\nFor $1 \\le i \\le 32$ and $1 \\le k \\le 10$, define the indicator variables \n\\[\nc_{ki} =\n\\begin{cases}\n1, & i \\in A_k, \\\\\n0, & i \\notin A_k.\n\\end{cases}\n\\] \nThen the size of the symmetric difference can be written as \n\\[\n\\bigl|D_i \\triangle D_j\\bigr| = \\sum_{k=1}^{10} (c_{ki} - c_{kj})^2.\n\\] \nHence, we can expand the total sum $S$ as follows: \n\\[\n\\begin{aligned}\n\\sum_{1 \\le i < j \\le 32} \\bigl|D_i \\triangle D_j\\bigr|^2\n&= \\sum_{1 \\le i < j \\le 32} \\left( \\sum_{k=1}^{10} (c_{ki} - c_{kj})^2 \\right)^2 \\\\\n&= \\sum_{1 \\le i < j \\le 32} \\sum_{k=1}^{10} (c_{ki} - c_{kj})^4 + 2 \\sum_{1 \\le i < j \\le 32} \\sum_{1 \\le k < l \\le 10} (c_{ki} - c_{kj})^2 (c_{li} - c_{lj})^2 \\\\\n&= \\sum_{k=1}^{10} \\sum_{1 \\le i < j \\le 32} (c_{ki} - c_{kj})^4 + 2 \\sum_{1 \\le k < l \\le 10} \\sum_{1 \\le i < j \\le 32} (c_{ki} - c_{kj})^2 (c_{li} - c_{lj})^2.\n\\end{aligned}\n\\] \n\nBecause for each $1 \\le k \\le 10$, among the $32$ values of $c_{ki}$ there are exactly $16$ ones and $16$ zeros, we have \n\\[\n\\sum_{1 \\le i < j \\le 32} (c_{ki} - c_{kj})^4 = 16 \\times 16 = 256,\n\\] \nso the first part of the sum is \n\\[\n\\sum_{k=1}^{10} \\sum_{1 \\le i < j \\le 32} (c_{ki} - c_{kj})^4 = 10 \\times 256 = 2560.\n\\] \n\nFor any fixed pair $1 \\le k < l \\le 10$, let $t$ be the number of indices $i$ for which $(c_{ki}, c_{li}) = (1, 1)$. Since both groups have exactly $16$ members, there are $16 - t$ indices with $(c_{ki}, c_{li}) = (1, 0)$, $16 - t$ indices with $(0, 1)$, and the remaining $32 - t - 2(16 - t) = t$ indices with $(0, 0)$. \n\nThe term $(c_{ki} - c_{kj})^2 (c_{li} - c_{lj})^2$ equals $1$ if and only if one of the indices $i, j$ corresponds to the pair of values $(1, 1)$ and the other to $(0, 0)$, or one corresponds to $(1, 0)$ and the other to $(0, 1)$. Consequently, \n\\[\n\\sum_{1 \\le i < j \\le 32} (c_{ki} - c_{kj})^2 (c_{li} - c_{lj})^2 = t^2 + (16 - t)^2 \\ge 2\\left(\\frac{16}{2}\\right)^2 = 128.\n\\] \nSumming this over all $\\binom{10}{2}$ pairs of groups $k < l$, we obtain \n\\[\n\\sum_{1 \\le k < l \\le 10} \\sum_{1 \\le i < j \\le 32} (c_{ki} - c_{kj})^2 (c_{li} - c_{lj})^2 \\ge \\binom{10}{2} \\times 128 = 45 \\times 128 = 5760.\n\\] \n\nThus, the total sum is bounded by \n\\[\nS \\ge 2560 + 2 \\times 5760 = 14080.\n\\] \n\nTo show that this minimum is attainable, we can construct a configuration where $t = 8$ for every pair of groups. It is easy to verify that each row of the following table contains $16$ ones and $16$ zeros, and any two rows have exactly $8$ positions where both are $1$ and $8$ positions where both are $0$, meaning equality holds:\n\n\\[\n\\begin{array}{c|c}\n\\hline\nA_1 & 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0 \\\\\nA_2 & 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0 \\\\\nA_3 & 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1 \\\\\nA_4 & 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0 \\\\\nA_5 & 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1 \\\\\nA_6 & 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0 \\\\\nA_7 & 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1\\; 1\\; 1\\; 0\\; 0\\; 0\\; 0\\; 1\\; 1 \\\\\nA_8 & 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0 \\\\\nA_9 & 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1\\; 1\\; 0\\; 0\\; 1 \\\\\nA_{10} & 1\\; 1\\; 0\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 0\\; 1\\; 0\\; 1\\; 1\\; 0\\; 0\\; 0\\; 1\\; 1\\; 0\\; 1\\; 0\\; 1\\; 0\\; 1\\; 1\\; 0\\; 1\\; 0\\; 0\\; 1 \\\\\n\\hline\n\\end{array}\n\\]\n\n*(Remark: Using Hadamard matrices, one can construct such an optimal configuration for up to $31$ interest groups.)*\n\nTherefore, the smallest possible value of $S$ is $14080$.", "grading_guidelines": "(Partial) 1. Reformulated the problem with indicator variables (or vectors) and obtained the identity |Di△Dj|=∑k(c_{ki}−c_{kj})^2, hence S=∑_{i<j}(∑k(c_{ki}−c_{kj})^2)^2. 2. Correctly computed the “diagonal” contribution: for each fixed group k with 16 ones and 16 zeros, proved ∑_{i<j}(c_{ki}−c_{kj})^4=16·16=256, hence the total first term is 10·256=2560. 3. For a fixed pair of groups k<l, introduced t=|Ak∩Al| and correctly derived that the cross-term sum equals t^2+(16−t)^2 (or an equivalent expression), and concluded its minimum is 128 attained at t=8. (Almost) 1. Obtained the bound S≥2560+2·(45·128)=14080 by summing the pairwise inequality t^2+(16−t)^2≥128 over all group-pairs, but did not provide (or only vaguely sketched) a configuration achieving equality. 2. Gave an explicit construction intended to have |Ak|=16 and |Ak∩Al|=8 for all k≠l (e.g. a 10×32 0–1 table / Hadamard-type pattern) but did not fully verify one of: each row has 16 ones, each pair of rows has exactly 8 common ones (equivalently also 8 common zeros), or that this indeed forces equality in the S bound. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Provide an explicit construction for the group assignments that achieves the minimum possible value of $S$.\n\nConstruction requirements:\n- Output a single Python list of lists of strings.\n- The matrix must have exactly 10 rows (representing the 10 interest groups) and 32 columns (representing the 32 students).\n- Each string element must be either \"0\" or \"1\", where \"1\" at row `i` and column `j` indicates that student `j` is in group `i`.\n- Each group (row) must contain exactly 16 students (i.e., exactly 16 \"1\"s and 16 \"0\"s).\n- The sum of interest differences $S$ over all $\\binom{32}{2}$ pairs of students must be exactly the minimum possible value.\n- Put ONLY the Python list of lists inside the construction block.", "ref_construction": "[\n [\"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\"],\n [\"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\"],\n [\"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\"],\n [\"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\"],\n [\"1\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"1\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"1\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"1\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\"],\n [\"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\"],\n [\"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"1\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"1\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"1\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"1\", \"0\"],\n [\"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\"],\n [\"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\"],\n [\"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\"]\n]", "verify_code": "import sys\nimport ast\n\ndef verify():\n input_str = sys.stdin.read().strip()\n if not input_str:\n print(\"Empty input.\")\n return\n\n try:\n matrix = ast.literal_eval(input_str)\n except Exception as e:\n print(f\"Failed to parse input as Python literal: {e}\")\n return\n\n if not isinstance(matrix, list):\n print(\"Input must be a list.\")\n return\n \n if len(matrix) != 10:\n print(f\"Matrix must have exactly 10 rows, found {len(matrix)}.\")\n return\n\n for i, row in enumerate(matrix):\n if not isinstance(row, list):\n print(f\"Row {i} is not a list.\")\n return\n if len(row) != 32:\n print(f\"Row {i} must have exactly 32 columns, found {len(row)}.\")\n return\n \n for j, val in enumerate(row):\n if not isinstance(val, str):\n print(f\"Element at ({i}, {j}) is not a string.\")\n return\n if val not in [\"0\", \"1\"]:\n print(f\"Element at ({i}, {j}) is '{val}', but must be '0' or '1'.\")\n return\n \n num_ones = sum(1 for val in row if val == \"1\")\n if num_ones != 16:\n print(f\"Row {i} has {num_ones} '1's, but must have exactly 16.\")\n return\n\n S = 0\n for u in range(32):\n for v in range(u + 1, 32):\n diff_count = 0\n for k in range(10):\n if matrix[k][u] != matrix[k][v]:\n diff_count += 1\n S += diff_count ** 2\n\n if S != 14080:\n print(f\"Sum of interest differences S is {S}, but must be exactly 14080.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "CMO-2018-P5", "category": "Operations and Strategies", "id": "CMO-2018-P5-101", "query": "Given a positive integer $n$, fill each cell of an $n \\\\times n$ grid with an integer. The following operation is performed on the grid: select a cell, and add $1$ to each of the $2n-1$ numbers in the row and column containing that cell. Find the largest positive integer $N$ such that, regardless of the initial numbers in the grid, it is always possible to perform a finite sequence of the above operations so that at least $N$ numbers in the grid are even.", "ref_answer": "When $n$ is even, it is $n^2$, and when $n$ is odd, it is $n^2-n+1$", "ref_solution": "Let $(i,j)$ denote the cell in row $i$ and column $j$.\n\n**Case 1: $n$ is even.**\nTo flip the parity of a specific cell $(i,j)$ without changing the parity of any other cell, we perform one operation on each of the $2n-1$ cells $(p,q)$ that lie in row $i$ or column $j$ (i.e., $p=i$ or $q=j$).\nThese operations affect the cell $(i,j)$ exactly $2n-1$ times, each of the other cells in row $i$ and column $j$ exactly $n$ times, and each cell neither in row $i$ nor in column $j$ exactly $2$ times.\nSince $n$ is even, $2n-1$ is odd, while $n$ and $2$ are even. Thus, the result of these operations is to flip the parity of the number in cell $(i,j)$ while leaving the parity of the numbers in all other cells unchanged.\nHence, by a sequence of such operations, we can independently adjust the parity of every cell, making all numbers in the grid even.\nClearly $N \\le n^2$, so in this case the maximum value of $N$ is $n^2$.\n\n**Case 2: $n$ is odd.**\nWhen $n$ is odd, $n-1$ is even. By restricting our chosen operation cells to the upper-left $(n-1) \\times (n-1)$ subgrid, the previous analysis shows that we can flip the parity of any target cell in this subgrid without altering the parity of any other cell within the subgrid. Thus, by a sequence of operations, we can make the numbers in the upper-left $(n-1)^2$ cells all even.\n\nIf at this point the number of even entries in row $n$ and column $n$ is less than $n$, then performing one operation on cell $(n,n)$ can increase the number of evens in row $n$ and column $n$ to at least $n$. (Note that row $n$ and column $n$ contain exactly $2n-1$ cells in total. If fewer than $n$ are even, then at least $n$ are odd. The operation on $(n,n)$ flips the parities of all these $2n-1$ cells without affecting the upper-left $(n-1) \\times (n-1)$ subgrid.)\nThus, by a sequence of operations we can ensure that the grid contains at least $(n-1)^2+n = n^2-n+1$ even numbers.\n\nOn the other hand, consider an initial grid where the cells $(1,1),(1,2),\\dots,(1,n-1)$ contain $1$ and all other cells contain $0$.\nIn this grid, the row sums of the first $n-1$ rows are even (the first row sum is $n-1$, which is even since $n$ is odd, and the others are $0$), and the column sums of the first $n-1$ columns are odd (each is $1$).\n\nNote that a single operation flips the parity of every row sum and column sum. Indeed, an operation on cell $(i,j)$ adds $1$ to the $2n-1$ cells in row $i$ and column $j$; the sum of any row $x$ increases by $n$ if $x=i$ and by $1$ if $x \\neq i$. Since $n$ is odd, the sum of every row increases by an odd amount, flipping its parity. By symmetry, the parity of every column sum also flips.\n\nTherefore, after an odd number of operations, the row sums of the first $n-1$ rows become odd; after an even number of operations, the column sums of the first $n-1$ columns become odd.\nIn either case, either the first $n-1$ rows all have an odd sum, or the first $n-1$ columns all have an odd sum. An odd sum requires at least one odd number in that row or column. Since the rows (or columns) are disjoint, the grid always contains at least $n-1$ odd numbers, implying $N \\le n^2 - (n-1) = n^2-n+1$.\nThus, in this case the maximum value of $N$ is $n^2-n+1$.", "grading_guidelines": "(Partial) 1. For even n, gave an explicit operation pattern that flips the parity of exactly one chosen cell while leaving all other cells’ parities unchanged (e.g., operating on all cells in its row and column), and correctly concluded that all n^2 cells can be made even. 2. For odd n, correctly reduced to controlling parities inside an (n−1)×(n−1) subgrid (using that n−1 is even) and showed one can make all entries in that subgrid even. 3. For odd n, established a valid invariant/obstruction using parities of row sums and column sums (e.g., each move flips the parity of every row sum and every column sum), and derived that at least n−1 entries must remain odd for a specific initial configuration. (Almost) 1. Correctly obtained the bound N=n^2 for even n and N=n^2−n+1 for odd n, but left a small gap in the parity-count of the “single-cell flip” construction (e.g., not fully justifying why all other cells are affected an even number of times). 2. For odd n, completed the construction achieving (n−1)^2+n even entries, but did not fully justify the step that an operation at (n,n) increases the number of evens in row n ∪ column n to at least n (i.e., the counting argument among 2n−1 parities). 3. For odd n, proved the row/column-sum invariant and set up the extremal initial configuration, but made a localized mistake in concluding that this forces at least n−1 odd cells in every reachable state (e.g., missing the disjointness argument or mixing the two cases of move parity).", "instruction": "Consider the specific case where $n = 101$. Construct a $101 \\times 101$ grid where each cell contains either 0 or 1.\nLet $M$ be the maximum number of even numbers that can be achieved in the grid after applying any finite sequence of the described operations. Your objective is to design the initial grid such that $M$ is minimized.\n\nConstruction format requirements:\n- Output a single Python expression (e.g., a list comprehension) that evaluates to a list of lists of integers (0s and 1s) representing the $101 \\times 101$ matrix.\n- The expression must be self-contained and evaluate directly to the matrix when passed to Python's `eval()`.\n- Do not include any explanations, comments, markdown code blocks, print statements, assignments, function definitions, imports, classes, asserts, or statement-level `for` loops.\n- Use list comprehensions, conditional expressions, and integer constants to generate the grid compactly.\n- Put ONLY the raw Python expression inside the construction block.", "ref_construction": "[[1 if i == 0 and j < 100 else 0 for j in range(101)] for i in range(101)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Validation error: Empty input.\")\n return\n \n try:\n # Use eval to evaluate the Python expression (e.g., list comprehensions)\n A = eval(payload)\n except Exception as e:\n print(f\"Parse error: Failed to evaluate payload: {e}\")\n return\n\n if type(A) is not list:\n print(f\"Validation error: Matrix A must be a list, got {type(A).__name__}.\")\n return\n \n if len(A) != 101:\n print(f\"Validation error: Matrix A must have exactly 101 rows, got {len(A)}.\")\n return\n \n for i, row in enumerate(A):\n if type(row) is not list:\n print(f\"Validation error: Row {i} is not a list, got {type(row).__name__}.\")\n return\n if len(row) != 101:\n print(f\"Validation error: Row {i} must have exactly 101 elements, got {len(row)}.\")\n return\n for j, val in enumerate(row):\n # Strictly check for integer 0 or 1 (rejecting booleans like False/True)\n if type(val) is not int or val not in (0, 1):\n print(f\"Validation error: Element at ({i}, {j}) must be the integer 0 or 1, got {repr(val)}.\")\n return\n\n # Compute row sums mod 2 and column sums mod 2\n row_sums = [sum(row) % 2 for row in A]\n col_sums = [sum(A[i][j] for i in range(101)) % 2 for j in range(101)]\n\n # Count the number of odd row sums (R0) and odd column sums (C0)\n R0 = sum(row_sums)\n C0 = sum(col_sums)\n\n # Compute the number of even row sums (R1) and even column sums (C1)\n R1 = 101 - R0\n C1 = 101 - C0\n\n # Calculate the minimum number of odd cells present in any reachable configuration\n min_odd_cells = min(max(R0, C0), max(R1, C1))\n \n # Subtract this from total cells to determine maximum guaranteed even numbers M\n M = 101**2 - min_odd_cells\n\n # Assert that M is exactly 10101\n if M != 10101:\n print(f\"Validation error: Expected maximum guaranteed even numbers M to be 10101, but got {M}.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "CMO-2014-P5", "category": "Graph Theory", "id": "CMO-2014-P5", "query": "A meeting has $30$ participants. It is known that each person has at most $5$ acquaintances among the others, and in any group of $5$ people, there exist two who are not acquaintances. Find the largest positive integer $k$ such that, under the given conditions, there always exist $k$ people who are pairwise non-acquaintances.", "ref_answer": "$k=6$", "ref_solution": "The largest positive integer $k$ is $6$.\n\nWe model the problem using a simple graph $G$. Let the $30$ participants be represented by $30$ vertices, and draw an edge between two vertices if the corresponding people are acquaintances. Let $V$ denote the vertex set of $G$. By the given conditions, every vertex in $G$ has degree at most $5$, and any set of $5$ vertices contains at least two vertices that are not adjacent. We are looking for the largest integer $k$ such that $G$ always contains an independent set of size at least $k$.\n\nFirst, we prove that the size of a maximum independent set in $G$ is at least $6$. \nLet $X$ be a maximum independent set of $G$. By the maximality of $X$, every vertex in $V \\setminus X$ must be adjacent to at least one vertex in $X$. (Otherwise, if some $a \\in V \\setminus X$ were not adjacent to any vertex in $X$, we could add $a$ to $X$ to obtain a strictly larger independent set, a contradiction.) Since each vertex in $X$ has degree at most $5$, the number of edges between $X$ and $V \\setminus X$ is at most $5|X|$. Thus, we have\n$$ 5|X| \\ge |V \\setminus X| = 30 - |X|, $$\nwhich yields $6|X| \\ge 30$, so $|X| \\ge 5$.\n\nIf $|X| = 5$, then the inequality $5|X| \\ge 30 - |X|$ becomes an equality. This implies that each vertex in $X$ is adjacent to exactly $5$ vertices in $V \\setminus X$, and the neighbor sets of any two distinct vertices in $X$ are disjoint. Let $X = \\{a, b, c, d, e\\}$, and let the neighbor set of $a$ be\n$$ Y_a = \\{y_1, y_2, y_3, y_4, y_5\\}. $$\nBy the problem condition, among the $5$ vertices in $Y_a$, there must be two that are not adjacent; without loss of generality, let them be $y_1$ and $y_2$. Since the neighbor sets of the vertices in $X$ are disjoint, neither $y_1$ nor $y_2$ is adjacent to any of $b, c, d, e$. Therefore,\n$$ \\{y_1, y_2, b, c, d, e\\} $$\nis an independent set in $G$ of size $6$, contradicting the assumption that the maximum independent set $X$ has size $5$. Hence, we must have $|X| \\ge 6$.\n\nNext, we prove that there exists a graph $G$ satisfying the conditions for which the maximum independent set has exactly $6$ vertices. \nPartition the vertex set $V$ into three subsets $V_1, V_2, V_3$ such that\n$$ |V_1| = |V_2| = |V_3| = 10. $$\nLet $V_1 = \\{a_1, a_2, \\dots, a_{10}\\}$. We define the edges within $V_1$ by declaring that $a_i$ is adjacent to\n$$ a_{i+1}, \\; a_{i+4}, \\; a_{i+5}, \\; a_{i+6}, \\; a_{i+9}, $$\nwhere the indices are taken modulo $10$. We define the edges within $V_2$ and $V_3$ in exactly the same way. For $1 \\le i < j \\le 3$, there are no edges between $V_i$ and $V_j$.\n\nWe now verify that this graph $G$ meets all the required conditions:\n\n1. Every vertex of $G$ has degree exactly $5$.\n\n2. Any $5$ vertices in $G$ contain two vertices that are not adjacent. It suffices to check that there is no clique of size $5$. Any such clique would have to be contained entirely within one component, say $V_1$. If it contains $a_i$, the other $4$ vertices must be chosen from its neighbors $a_{i+1}, a_{i+4}, a_{i+5}, a_{i+6}, a_{i+9}$. However, $a_{i+1}$ is not adjacent to $a_{i+4}$, and $a_{i+6}$ is not adjacent to $a_{i+9}$. Thus, it is impossible to choose $4$ pairwise adjacent neighbors of $a_i$.\n\n3. The maximum independent set in $G$ has size $6$. Suppose $a_{i_1}, a_{i_2}, a_{i_3}$ are three distinct vertices in $V_1$ such that $a_{i_1}$ is not adjacent to $a_{i_2}$, and $a_{i_2}$ is not adjacent to $a_{i_3}$. By the construction of $V_1$, non-adjacent vertices must have index differences of $2$ or $3$ modulo $10$. Thus,\n$$ |i_1 - i_2| \\equiv 2 \\text{ or } 3 \\pmod{10}, \\qquad |i_2 - i_3| \\equiv 2 \\text{ or } 3 \\pmod{10}. $$\nIt follows that the non-zero difference $|i_1 - i_3| \\pmod{10}$ must be one of $\\pm 1, \\pm 4, \\text{ or } 5$. Since all these differences correspond to adjacent vertices, $a_{i_1}$ and $a_{i_3}$ must be adjacent. This shows that the largest independent set in $V_1$ has size at most $2$. Consequently, the largest independent set in $G$ has size $2 \\times 3 = 6$.\n\nWe conclude that the largest positive integer $k$ is $6$.", "grading_guidelines": "(Partial) 1. Modeled the problem as a graph and identified the goal as finding a lower bound on the independence number (and/or an upper bound via a construction). 2. Proved the basic bound using a maximal independent set X and degree ≤5: every vertex outside X is adjacent to X, hence 5|X| ≥ 30−|X| and so |X| ≥ 5. 3. Used the “any 5 vertices contain two non-adjacent” condition to exclude some small-clique configuration (e.g. observed that the graph has no K5). 4. Gave a plausible extremal construction idea (e.g. disjoint union of 3 graphs on 10 vertices each with maximum independent set 2), but did not fully verify the required properties. (Almost) 1. Proved |X|≥6 via the maximal independent set counting argument and the equality case |X|=5 leading to disjoint neighbor sets, but left a small gap in deriving the disjointness/forcing the equality structure. 2. Completed the lower bound and presented a construction intended to show k≤6, but did not fully check one of: degree ≤5, absence of a 5-clique (the “any 5 contain two non-adjacent” condition), or that the maximum independent set in the construction is exactly 6. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Construct an explicit 30x30 adjacency matrix representing the acquaintance graph that proves the boundary value $k$ is tight. \n\nOutput requirements:\n- The construction must be a single Python expression. Evaluating this expression must directly return the required 30x30 adjacency matrix.\n- The value of the expression must be a single Python list of lists representing the 30x30 adjacency matrix.\n- Use 0 and 1 for the matrix elements.\n- The matrix must represent an undirected simple graph (it must be symmetric, with 0s on the main diagonal).\n- The graph must satisfy the constraints: max degree $\\le 5$, and no clique of size 5 ($K_5$).\n- The maximum independent set size of the graph must be exactly the boundary value $k$ implied by the problem.\n- Do not use explanations, comments, assignments, imports, function definitions, or any non-expression content.\n- Put ONLY the Python expression inside the `<construct>` block.", "ref_construction": "[[int(i != j and (((j // 6 - i // 6) % 5, (j % 6 - i % 6) % 6) in {(0, 3), (1, 0), (1, 3), (4, 0), (4, 3)})) for j in range(30)] for i in range(30)]", "verify_code": "import sys\nimport itertools\n\ndef solve():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n try:\n matrix = eval(payload, {\"__builtins__\": {}, \"range\": range, \"int\": int}, {})\n except Exception as e:\n print(f\"Failed to evaluate construction: {e}\")\n return\n\n if not isinstance(matrix, list) or len(matrix) != 30:\n print(\"Matrix must be a list of 30 rows.\")\n return\n for i, row in enumerate(matrix):\n if not isinstance(row, list) or len(row) != 30:\n print(f\"Row {i} must be a list of 30 elements.\")\n return\n for j, val in enumerate(row):\n if val not in (0, 1):\n print(f\"Element at ({i}, {j}) is not 0 or 1.\")\n return\n\n for i in range(30):\n if matrix[i][i] != 0:\n print(f\"Diagonal element at ({i}, {i}) is not 0.\")\n return\n for j in range(30):\n if matrix[i][j] != matrix[j][i]:\n print(f\"Matrix is not symmetric at ({i}, {j}).\")\n return\n\n for i in range(30):\n deg = sum(matrix[i])\n if deg > 5:\n print(f\"Vertex {i} has degree {deg} > 5.\")\n return\n\n for i in range(30):\n neighbors = [j for j in range(30) if matrix[i][j] == 1]\n if len(neighbors) >= 4:\n for combo in itertools.combinations(neighbors, 4):\n is_clique = True\n for u, v in itertools.combinations(combo, 2):\n if matrix[u][v] == 0:\n is_clique = False\n break\n if is_clique:\n print(f\"Found a clique of size 5 including vertex {i}: {tuple([i] + list(combo))}\")\n return\n\n def get_max_independent_set_size(adj):\n n = len(adj)\n max_size = 0\n comp_neighbors = [0] * n\n for i in range(n):\n for j in range(n):\n if i != j and adj[i][j] == 0:\n comp_neighbors[i] |= (1 << j)\n\n def bk(r, p, x):\n nonlocal max_size\n r_count = bin(r).count('1')\n p_count = bin(p).count('1')\n\n if p == 0 and x == 0:\n if r_count > max_size:\n max_size = r_count\n return\n\n if r_count + p_count <= max_size:\n return\n\n pivot = -1\n max_p_intersect = -1\n union_px = p | x\n temp = union_px\n while temp > 0:\n lsb = temp & -temp\n i = lsb.bit_length() - 1\n intersect = p & comp_neighbors[i]\n c = bin(intersect).count('1')\n if c > max_p_intersect:\n max_p_intersect = c\n pivot = i\n temp &= temp - 1\n\n explore = p & ~comp_neighbors[pivot] if pivot != -1 else p\n while explore > 0:\n v = explore & -explore\n v_idx = v.bit_length() - 1\n bk(r | v, p & comp_neighbors[v_idx], x & comp_neighbors[v_idx])\n p &= ~v\n x |= v\n explore &= ~v\n\n bk(0, (1 << n) - 1, 0)\n return max_size\n\n mis_size = get_max_independent_set_size(matrix)\n if mis_size != 6:\n print(f\"Maximum independent set size is {mis_size}, expected exactly 6.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n solve()"} | |
| {"split": "construction", "source": "CMO-2012-P2", "category": "Counting", "id": "CMO-2012-P2", "query": "\"Given a prime number $p$. Let $A = (a_{ij})$ be a $p \\\\times p$ matrix such that $\\\\{a_{ij} \\\\mid 1 \\\\leq i, j \\\\leq p\\\\} = \\\\{1, 2, \\\\cdots, p^2\\\\}$. The following operation is allowed: choose a row or a column, and simultaneously add $1$ or subtract $1$ to each number in that row or column. If it is possible to turn all elements of $A$ into $0$ after finitely many such operations, then $A$ is called a \\\"\"good matrix\\\"\". Find the number of \\\"\"good matrices\\\"\".\n\"", "ref_answer": "$2(p!)^2$", "ref_solution": "Let the operations applied to the rows and columns be represented by subtracting $x_i$ from row $i$ and $y_j$ from column $j$. The matrix can be turned into the zero matrix if and only if the original entries satisfy $a_{ij} = x_i + y_j$ for some integers $x_i$ and $y_j$ for all $1 \\le i, j \\le p$. \n\nSince the entries of the matrix are a permutation of $\\{1, 2, \\dots, p^2\\}$, we have \n\\[\n\\{x_i + y_j \\mid 1 \\le i, j \\le p\\} = \\{1, 2, \\dots, p^2\\}.\n\\]\nLet us define the polynomials \n\\[\nf(z) = \\sum_{i=1}^{p} z^{x_i} \\quad \\text{and} \\quad g(z) = \\sum_{j=1}^{p} z^{y_j}.\n\\]\nThen, the condition on the sums $x_i + y_j$ translates to the polynomial identity\n\\[\nf(z)g(z) = z + z^2 + \\cdots + z^{p^2}.\n\\]\nWe can factor the right-hand side as\n\\[\nz + z^2 + \\cdots + z^{p^2} = z(1 + z + \\cdots + z^{p-1})(1 + z^p + \\cdots + z^{p(p-1)}).\n\\]\nBecause the cyclotomic polynomials $\\Phi_p(z) = 1 + z + \\cdots + z^{p-1}$ and $\\Phi_{p^2}(z) = 1 + z^p + \\cdots + z^{p(p-1)}$ are both irreducible, and $f(1) = g(1) = p$, each of $f(z)$ and $g(z)$ must be the product of a monomial $z^a$ and exactly one of $\\Phi_p(z)$ or $\\Phi_{p^2}(z)$. Consequently, the set $\\{x_1, x_2, \\dots, x_p\\}$ must be one of the following:\n\\[\n\\{0, 1, \\dots, p-1\\} \\quad \\text{or} \\quad \\{1, p+1, \\dots, p(p-1)+1\\} \\quad \\text{or} \\quad \\{1, 2, \\dots, p\\} \\quad \\text{or} \\quad \\{0, p, \\dots, p(p-1)\\}.\n\\]\nFrom this, it is easy to obtain the solution to the original problem, yielding a total of $2(p!)^2$ good matrices.", "grading_guidelines": "(Partial) 1. Reformulated the operations: showed that $A$ is good iff there exist integers $(x_i)_{i=1}^p,(y_j)_{j=1}^p$ with $a_{ij}=x_i+y_j$ for all $i,j$ (equivalently, all $2\\times2$ minors satisfy $a_{ij}+a_{kl}=a_{il}+a_{kj}$). 2. Set up the generating-function identity $f(z)=\\sum_{i=1}^p z^{x_i},\\ g(z)=\\sum_{j=1}^p z^{y_j}$ and derived $f(z)g(z)=z+z^2+\\cdots+z^{p^2}$ from the multiset condition $\\{x_i+y_j\\}=\\{1,2,\\dots,p^2\\}$. 3. From the identity (or from modular/spacing considerations), correctly obtained at least one of the two structural possibilities: either $\\{x_i\\}$ is a translate of $\\{0,1,\\dots,p-1\\}$ and $\\{y_j\\}$ is a translate of $\\{0,p,2p,\\dots,(p-1)p\\}$, or the swapped roles of rows/columns. (Almost) 1. Completed the classification of possible exponent sets (up to translation): proved that $\\{x_i\\}$ and $\\{y_j\\}$ must correspond to the two cyclotomic factors (hence to one of the two “arithmetic progression mod $p$ / progression step $p$” patterns), but did not finish converting this into the final count $2(p!)^2$. 2. Counted the matrices once the two patterns for $(x_i),(y_j)$ are identified, but missed a global shift/normalization issue (e.g. double-counted or forgot the symmetry swapping rows and columns), leading to an answer off by a factor of $2$ or by a constant factor. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For the specific case $p=3$, provide an explicit construction of all valid \"good matrices\".\n\nConstruction requirements:\n- Output a single Python list containing all such matrices.\n- Each matrix must be represented as a list of 3 lists, where each inner list represents a row of 3 integers.\n- The matrices can be listed in any order, but there must be no duplicates.\n- Your output must be exhaustive, including every possible good matrix exactly once.\n- Each matrix must contain all integers from 1 to 9 exactly once.\n- Each matrix must be a \"good matrix\" according to the problem definition (i.e., it can be reduced to the zero matrix by the allowed operations).\n- Put ONLY the Python literal list of lists of lists inside the construction block.", "ref_construction": "[\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n [[1, 3, 2], [4, 6, 5], [7, 9, 8]],\n [[2, 1, 3], [5, 4, 6], [8, 7, 9]],\n [[2, 3, 1], [5, 6, 4], [8, 9, 7]],\n [[3, 1, 2], [6, 4, 5], [9, 7, 8]],\n [[3, 2, 1], [6, 5, 4], [9, 8, 7]],\n [[1, 2, 3], [7, 8, 9], [4, 5, 6]],\n [[1, 3, 2], [7, 9, 8], [4, 6, 5]],\n [[2, 1, 3], [8, 7, 9], [5, 4, 6]],\n [[2, 3, 1], [8, 9, 7], [5, 6, 4]],\n [[3, 1, 2], [9, 7, 8], [6, 4, 5]],\n [[3, 2, 1], [9, 8, 7], [6, 5, 4]],\n [[4, 5, 6], [1, 2, 3], [7, 8, 9]],\n [[4, 6, 5], [1, 3, 2], [7, 9, 8]],\n [[5, 4, 6], [2, 1, 3], [8, 7, 9]],\n [[5, 6, 4], [2, 3, 1], [8, 9, 7]],\n [[6, 4, 5], [3, 1, 2], [9, 7, 8]],\n [[6, 5, 4], [3, 2, 1], [9, 8, 7]],\n [[4, 5, 6], [7, 8, 9], [1, 2, 3]],\n [[4, 6, 5], [7, 9, 8], [1, 3, 2]],\n [[5, 4, 6], [8, 7, 9], [2, 1, 3]],\n [[5, 6, 4], [8, 9, 7], [2, 3, 1]],\n [[6, 4, 5], [9, 7, 8], [3, 1, 2]],\n [[6, 5, 4], [9, 8, 7], [3, 2, 1]],\n [[7, 8, 9], [1, 2, 3], [4, 5, 6]],\n [[7, 9, 8], [1, 3, 2], [4, 6, 5]],\n [[8, 7, 9], [2, 1, 3], [5, 4, 6]],\n [[8, 9, 7], [2, 3, 1], [5, 6, 4]],\n [[9, 7, 8], [3, 1, 2], [6, 4, 5]],\n [[9, 8, 7], [3, 2, 1], [6, 5, 4]],\n [[7, 8, 9], [4, 5, 6], [1, 2, 3]],\n [[7, 9, 8], [4, 6, 5], [1, 3, 2]],\n [[8, 7, 9], [5, 4, 6], [2, 1, 3]],\n [[8, 9, 7], [5, 6, 4], [2, 3, 1]],\n [[9, 7, 8], [6, 4, 5], [3, 1, 2]],\n [[9, 8, 7], [6, 5, 4], [3, 2, 1]],\n [[1, 4, 7], [2, 5, 8], [3, 6, 9]],\n [[1, 4, 7], [3, 6, 9], [2, 5, 8]],\n [[2, 5, 8], [1, 4, 7], [3, 6, 9]],\n [[2, 5, 8], [3, 6, 9], [1, 4, 7]],\n [[3, 6, 9], [1, 4, 7], [2, 5, 8]],\n [[3, 6, 9], [2, 5, 8], [1, 4, 7]],\n [[1, 7, 4], [2, 8, 5], [3, 9, 6]],\n [[1, 7, 4], [3, 9, 6], [2, 8, 5]],\n [[2, 8, 5], [1, 7, 4], [3, 9, 6]],\n [[2, 8, 5], [3, 9, 6], [1, 7, 4]],\n [[3, 9, 6], [1, 7, 4], [2, 8, 5]],\n [[3, 9, 6], [2, 8, 5], [1, 7, 4]],\n [[4, 1, 7], [5, 2, 8], [6, 3, 9]],\n [[4, 1, 7], [6, 3, 9], [5, 2, 8]],\n [[5, 2, 8], [4, 1, 7], [6, 3, 9]],\n [[5, 2, 8], [6, 3, 9], [4, 1, 7]],\n [[6, 3, 9], [4, 1, 7], [5, 2, 8]],\n [[6, 3, 9], [5, 2, 8], [4, 1, 7]],\n [[4, 7, 1], [5, 8, 2], [6, 9, 3]],\n [[4, 7, 1], [6, 9, 3], [5, 8, 2]],\n [[5, 8, 2], [4, 7, 1], [6, 9, 3]],\n [[5, 8, 2], [6, 9, 3], [4, 7, 1]],\n [[6, 9, 3], [4, 7, 1], [5, 8, 2]],\n [[6, 9, 3], [5, 8, 2], [4, 7, 1]],\n [[7, 1, 4], [8, 2, 5], [9, 3, 6]],\n [[7, 1, 4], [9, 3, 6], [8, 2, 5]],\n [[8, 2, 5], [7, 1, 4], [9, 3, 6]],\n [[8, 2, 5], [9, 3, 6], [7, 1, 4]],\n [[9, 3, 6], [7, 1, 4], [8, 2, 5]],\n [[9, 3, 6], [8, 2, 5], [7, 1, 4]],\n [[7, 4, 1], [8, 5, 2], [9, 6, 3]],\n [[7, 4, 1], [9, 6, 3], [8, 5, 2]],\n [[8, 5, 2], [7, 4, 1], [9, 6, 3]],\n [[8, 5, 2], [9, 6, 3], [7, 4, 1]],\n [[9, 6, 3], [7, 4, 1], [8, 5, 2]],\n [[9, 6, 3], [8, 5, 2], [7, 4, 1]]\n]", "verify_code": "import sys\nimport ast\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty payload.\")\n return\n \n try:\n matrices = ast.literal_eval(payload)\n except Exception as e:\n print(f\"Failed to parse payload as Python literal: {e}\")\n return\n \n if not isinstance(matrices, list):\n print(\"The payload must be a list.\")\n return\n \n if len(matrices) != 72:\n print(f\"Expected exactly 72 matrices, but got {len(matrices)}.\")\n return\n \n unique_matrices = set()\n \n for idx, matrix in enumerate(matrices):\n if not isinstance(matrix, list) or len(matrix) != 3:\n print(f\"Matrix at index {idx} is not a list of exactly 3 elements.\")\n return\n \n elements = []\n tuple_matrix = []\n for r_idx, row in enumerate(matrix):\n if not isinstance(row, list) or len(row) != 3:\n print(f\"Row {r_idx} of matrix at index {idx} is not a list of exactly 3 elements.\")\n return\n for val in row:\n if type(val) is not int:\n print(f\"Element {val} in matrix {idx} is not an integer.\")\n return\n elements.append(val)\n tuple_matrix.append(tuple(row))\n \n unique_matrices.add(tuple(tuple_matrix))\n \n if sorted(elements) != [1, 2, 3, 4, 5, 6, 7, 8, 9]:\n print(f\"Matrix at index {idx} does not contain exactly the integers 1 to 9.\")\n return\n \n for i in range(3):\n for j in range(3):\n if matrix[i][j] - matrix[i][0] != matrix[0][j] - matrix[0][0]:\n print(f\"Matrix at index {idx} is not a 'good matrix'. Failed property at i={i}, j={j}.\")\n return\n \n if len(unique_matrices) != 72:\n print(f\"Expected 72 unique matrices, but found {len(unique_matrices)}.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "RMO-2024-P5", "category": "Extremal Problems", "id": "RMO-2024-P5", "query": "A garden consists of a $10\\times10$ grid of squares. On New Year's Eve, it begins to snow, and from that point on, every night $10$ cm of snow falls on each square (snow only falls at night). Every morning, the gardener chooses one row or one column and shovels all the snow from it onto an adjacent row or column, with the rule that snow cannot be shoveled outside the garden. On the evening of the $100$th day of the new year, an inspector will arrive and find the highest snow pile. The gardener's goal is to minimize this height. Find the height of the snow pile found by the inspector. Note: The snow does not melt during these $100$ days.", "ref_answer": "1120 centimeters", "ref_solution": "On the morning of day $100$, the caretaker clears the snow from an entire row or column. Since snow only falls at night, by the evening of day $100$ (when the inspector arrives), there are $10$ cells in that cleared row or column with $0$ cm of snow. \n\nOver the $100$ days, a total of $100 \\times 100$ units of $10$-centimeter snow has fallen on the garden. Since the total amount of snow is conserved (none is shoveled outside or melts), these $10,000$ units of snow must be distributed among the remaining at most $90$ cells. By the averaging principle, there must be at least one cell containing at least\n$$ 10 \\left\\lceil \\frac{100 \\times 100}{90} \\right\\rceil = 10 \\lceil 111.11\\dots \\rceil = 1120 \\text{ cm} $$\nof snow. Thus, the maximum height of a snow pile is at least $1120$ cm.\n\nWe can achieve exactly $1120$ cm with the following strategy:\n- In the first $11$ days (days $1$ to $11$), the caretaker sweeps all the snow from the second column into the first column.\n- In the next $11$ days (days $12$ to $22$), the caretaker sweeps all the snow from the third column into the second column.\n- In general, for each $k = 1, 2, \\dots, 9$, during the $11$ days from day $11k - 10$ to day $11k$, the caretaker sweeps all the snow from column $k+1$ into column $k$.\n\nLet us track the amount of snow in each column. We claim that after $11k$ days, each cell in columns $1$ through $k$ has $110(k+1)$ cm of snow, each cell in column $k+1$ has $0$ cm, and each cell in columns $k+2$ through $10$ has $110k$ cm. We proceed by induction on $k$:\n- **Base case ($k=1$)**: During the first $11$ days, column $2$ is swept to column $1$ every morning. Each day, column $1$ receives its own $10$ cm of snowfall plus the $10$ cm of snow swept from column $2$, accumulating $20 \\times 11 = 220$ cm. Column $2$ is cleared every morning and thus ends with $0$ cm. Columns $3$ through $10$ are untouched and each accumulate $10 \\times 11 = 110$ cm. The claim holds.\n- **Inductive step**: Suppose the claim holds for $k$. During the next $11$ days (days $11k+1$ to $11k+11$), column $k+2$ is swept into column $k+1$.\n On the morning of day $11k+1$, column $k+2$ has its previous $110k$ cm plus $10$ cm from the overnight snowfall, totaling $110k + 10$ cm. This is swept into column $k+1$, which also received $10$ cm overnight. Thus, column $k+1$ now holds $10 + 110k + 10 = 110k + 20$ cm.\n For the remaining $10$ days of this $11$-day period, column $k+1$ receives its own $10$ cm plus the $10$ cm from column $k+2$ each day, gaining an additional $20 \\times 10 = 200$ cm. Thus, column $k+1$ reaches $110k + 20 + 200 = 110(k+2)$ cm.\n Column $k+2$ is cleared every morning and ends with $0$ cm.\n Columns $1$ through $k$ simply accumulate $10$ cm each night for $11$ nights, adding $110$ cm to reach $110(k+1) + 110 = 110(k+2)$ cm.\n Columns $k+3$ through $10$ also accumulate $110$ cm, reaching $110k + 110 = 110(k+1)$ cm.\n This completes the induction.\n\nApplying this for $k=9$, after $99$ days, each cell in columns $1$ through $9$ has $110(10) = 1100$ cm of snow, and each cell in column $10$ has $0$ cm. \n\nOn day $100$, $10$ cm of snow falls on all columns overnight. Columns $1$ through $9$ now have $1110$ cm, and column $10$ has $10$ cm. In the morning, the caretaker sweeps the snow from the tenth column into the ninth column. Each cell in column $9$ receives the $10$ cm from column $10$, reaching $1110 + 10 = 1120$ cm. Column $10$ is left with $0$ cm, and columns $1$ through $8$ remain at $1110$ cm. \n\nTherefore, on the evening of the $100$th day, the maximum snow pile height found by the inspector is exactly $1120$ cm.", "grading_guidelines": "(Partial) 1. Observed that on day 100 the gardener can create (at least) 10 cells with 0 cm by choosing a whole row/column to be cleared that morning, and used this to reduce the final distribution to at most 90 nonzero cells. 2. Used conservation of total snow and an averaging/pigeonhole argument to obtain a nontrivial lower bound for the maximum pile (e.g. deriving the bound 1120 cm, or correctly setting up 10000 units over 90 cells). 3. Gave a concrete, checkable shoveling strategy that keeps the maximum height bounded by a specific value close to the optimum (even if not proved optimal), e.g. a systematic column-by-column shifting plan. (Almost) 1. Proved the correct lower bound 1120 cm, but the construction is incomplete (e.g. strategy described but not tracked rigorously to ensure no cell exceeds 1120). 2. Presented the intended 11-day-per-column shifting strategy (or equivalent) and tracked column heights to reach a maximum of 1120 cm, but with a small arithmetic/indexing error (such as miscounting 99 vs 100 days) that is localized and fixable. 3. Gave both a correct lower bound via averaging and a near-complete matching strategy, but omitted a boundary check (e.g. the final day’s move or the fact that shoveling is to an adjacent row/column only) while the rest of the argument is correct.", "instruction": "Provide an explicit 100-day morning operation schedule that achieves the optimal minimization objective from the original problem.\n\nOutput exactly one construction block with ONLY a Python literal list of length 100 between the tags <construct> and </construct>. Each element must be a 3-tuple (kind, idx, dir) where:\n- kind is the string \"R\" (row) or \"C\" (column),\n- idx is an integer in {0,1,...,9} indicating which row/column is selected,\n- dir is either -1 or +1 indicating shoveling to the adjacent row/column with index idx+dir.\n\nOperational meaning to be verified (do not restate as extra text inside the construction):\n- Nights: for each day d = 1..100, before the morning operation, every one of the 100 squares gains +10 cm of snow.\n- Mornings: then execute the scheduled operation for that day: choose the specified full row/column, remove all its snow and add it cellwise onto the adjacent target row/column (same columns for a row move; same rows for a column move). The source row/column becomes 0 afterwards. Snow may not be shoveled outside the 10x10 grid, so idx+dir must be in {0..9}.\n\nThe verifier will simulate all 100 days in this time order and then compute, on the evening of day 100 (i.e., after the 100th morning operation), the maximum snow height over all squares; your schedule must attain the optimal bound for this instance.", "ref_construction": "[('R', 0, 1), ('R', 6, 1), ('R', 1, 1), ('R', 8, -1), ('R', 8, 1), ('R', 3, -1), ('R', 6, -1), ('R', 8, 1), ('R', 5, 1), ('R', 9, -1),\n ('R', 1, -1), ('R', 1, -1), ('R', 8, 1), ('R', 5, -1), ('R', 4, 1), ('R', 1, -1), ('R', 2, -1), ('R', 3, -1), ('R', 7, 1), ('R', 6, 1),\n ('R', 3, -1), ('R', 3, 1), ('R', 6, 1), ('R', 6, -1), ('R', 5, 1), ('R', 2, 1), ('R', 3, -1), ('R', 3, -1), ('R', 4, 1), ('R', 3, 1),\n ('R', 3, -1), ('R', 3, -1), ('R', 4, 1), ('R', 4, -1), ('R', 4, -1), ('R', 4, -1), ('R', 4, -1), ('R', 4, 1), ('R', 4, -1), ('R', 4, -1),\n ('R', 4, -1), ('R', 4, -1), ('R', 4, 1), ('R', 4, 1), ('R', 4, -1), ('R', 3, 1), ('R', 3, 1), ('R', 3, 1), ('R', 4, -1), ('R', 4, -1),\n ('R', 4, -1), ('R', 4, -1), ('R', 4, 1), ('R', 4, 1), ('R', 3, 1), ('R', 3, -1), ('R', 4, -1), ('R', 4, -1), ('R', 4, -1), ('R', 4, -1),\n ('R', 4, -1), ('R', 4, 1), ('R', 4, -1), ('R', 4, -1), ('R', 3, 1), ('R', 4, -1), ('R', 3, 1), ('R', 3, 1), ('R', 3, 1), ('R', 3, -1),\n ('R', 3, 1), ('R', 4, -1), ('R', 3, 1), ('R', 3, -1), ('R', 4, -1), ('R', 4, -1), ('R', 3, 1), ('R', 4, -1), ('R', 4, -1), ('R', 5, -1),\n ('R', 5, -1), ('R', 5, -1), ('R', 5, 1), ('R', 4, 1), ('R', 3, 1), ('R', 4, -1), ('R', 5, -1), ('R', 5, 1), ('R', 4, 1), ('R', 4, -1),\n ('R', 3, 1), ('R', 4, -1), ('R', 4, 1), ('R', 5, -1), ('R', 4, 1), ('R', 3, 1), ('R', 3, -1), ('R', 3, 1), ('R', 2, 1), ('R', 3, -1)]", "verify_code": "import sys, ast\n\nTARGET_MAX = 1120\nN = 10\nDAYS = 100\nFALL = 10\n\ndef fail(msg: str):\n print(msg)\n sys.exit(0)\n\ndef main():\n s = sys.stdin.read()\n if s.strip() == \"\":\n fail(\"Parse error: empty input (expected a Python literal list).\")\n try:\n obj = ast.literal_eval(s)\n except Exception as e:\n fail(f\"Parse error: {e}\")\n\n if not isinstance(obj, list):\n fail(f\"Validation error: expected a list, got {type(obj).__name__}.\")\n if len(obj) != DAYS:\n fail(f\"Validation error: expected list of length {DAYS}, got {len(obj)}.\")\n\n # grid[r][c] in centimeters\n grid = [[0 for _ in range(N)] for _ in range(N)]\n\n for day in range(DAYS):\n step = obj[day]\n if not isinstance(step, (tuple, list)) or len(step) != 3:\n fail(f\"Validation error (day {day+1}): expected a 3-tuple/list (kind, idx, dir).\")\n kind, idx, direction = step\n\n if kind not in (\"R\", \"C\"):\n fail(f\"Validation error (day {day+1}): kind must be 'R' or 'C'.\")\n if not isinstance(idx, int):\n fail(f\"Validation error (day {day+1}): idx must be an int.\")\n if idx < 0 or idx >= N:\n fail(f\"Validation error (day {day+1}): idx out of range 0..9.\")\n if direction not in (-1, 1):\n fail(f\"Validation error (day {day+1}): dir must be -1 or +1.\")\n dst = idx + direction\n if not isinstance(dst, int) or dst < 0 or dst >= N:\n fail(f\"Validation error (day {day+1}): illegal destination idx+dir={dst} (must be 0..9).\")\n\n # Night snowfall\n for r in range(N):\n row = grid[r]\n for c in range(N):\n row[c] += FALL\n\n # Morning operation\n if kind == \"R\":\n src = idx\n tgt = dst\n src_row = grid[src]\n tgt_row = grid[tgt]\n for c in range(N):\n tgt_row[c] += src_row[c]\n src_row[c] = 0\n else: # kind == \"C\"\n src = idx\n tgt = dst\n for r in range(N):\n grid[r][tgt] += grid[r][src]\n grid[r][src] = 0\n\n # Nonnegativity sanity\n for r in range(N):\n for c in range(N):\n if grid[r][c] < 0:\n fail(f\"Validation error (day {day+1}): negative snow height encountered.\")\n\n mx = max(max(row) for row in grid)\n if mx != TARGET_MAX:\n fail(f\"Validation failure: final maximum snow height is {mx} cm, expected {TARGET_MAX} cm.\")\n print(\"True\")\n\nif __name__ == \"__main__\":\n main()"} | |
| {"split": "construction", "source": "RMO-2019-P15", "category": "Existence and Construction", "id": "RMO-2019-P15", "query": "A math group has 24 students. For every team of 6 students, the supervisor gives one of two evaluations: \"can cooperate\" or \"cannot cooperate.\" For training in a math competition, the supervisor plans to divide the students into 4 teams, each with 6 students. Is it possible that for any division into 4 teams, either exactly three teams can cooperate or exactly one team can cooperate, and both cases occur?", "ref_answer": "can", "ref_solution": "Yes, it is possible. \n\nSelect three specific students from the 24. Evaluate any team of 6 students that contains exactly one or all three of these selected students as \"can cooperate\", and evaluate all other teams (those containing exactly zero or exactly two of the selected students) as \"cannot cooperate\". \n\nBelow we verify that this evaluation method satisfies the requirement. When the 24 students are divided into 4 teams of 6, the three selected students must be distributed among the four teams. The possible distributions of the three selected students are as follows:\n\n1. If the three selected students are placed in three different teams (a 1-1-1-0 distribution), then exactly three teams contain one selected student and one team contains zero. The three teams with one selected student are evaluated as \"can cooperate\", and the remaining team is evaluated as \"cannot cooperate\". Thus, exactly three teams can cooperate.\n2. If all three selected students are placed in the same team (a 3-0-0-0 distribution), then exactly one team contains three selected students and the other three contain zero. The team with three selected students is evaluated as \"can cooperate\", and the other three are evaluated as \"cannot cooperate\". Thus, exactly one team can cooperate.\n3. If two of the selected students are placed in the same team and the remaining one is placed in another team (a 2-1-0-0 distribution), then exactly one team contains one selected student, one team contains two, and two teams contain zero. The team containing exactly one selected student is evaluated as \"can cooperate\", while the team with two and the teams with zero are evaluated as \"cannot cooperate\". Thus, exactly one team can cooperate.\n\nSince the total number of selected students across the four teams is exactly 3, these are all the possible cases. In every division into 4 teams, either exactly three teams can cooperate or exactly one team can cooperate. \n\nFurthermore, since each team has a capacity of 6 students (which is sufficient to hold up to 3 selected students) and there are enough remaining students to fill the teams, we can easily construct divisions that achieve the 1-1-1-0 distribution and the 3-0-0-0 distribution. Thus, both outcomes (exactly 3 teams can cooperate, and exactly 1 team can cooperate) actually occur.\n\nHence, the proposition is proved.", "grading_guidelines": "(Partial) 1. Proposed a concrete evaluation rule depending only on how a 6-person team intersects a fixed small distinguished set of students (e.g. 3 chosen students), in a way intended to force the number of “can cooperate” teams in any 4-way partition to be 1 or 3. 2. Correctly analysed at least one nontrivial distribution pattern of the distinguished students among the four teams (e.g. 1-1-1-0 or 3-0-0-0 or 2-1-0-0) and deduced the corresponding number of “can cooperate” teams under the proposed rule. 3. Exhibited at least one explicit partition of the 24 students into four 6-person teams that achieves one of the two required outcomes (either exactly 1 cooperative team or exactly 3 cooperative teams). (Almost) 1. Gave essentially the intended construction (e.g. choose 3 special students; declare teams with exactly 1 or 3 of them as “can cooperate”, others as “cannot”) and checked the cooperative-team count for all distributions of the 3 special students among the four teams, but omitted a short justification that these are the only possible distributions. 2. Proved that in every 4-team division the number of cooperative teams is always either 1 or 3, but did not explicitly show that both outcomes actually occur (missing an explicit partition for one of the two cases). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For the 24 students (numbered 1 through 24), provide an explicit rule to determine whether any given 6-student team \"can cooperate\" or \"cannot cooperate\", and construct two specific partitions to demonstrate the required outcomes.\n\nRequirements:\n1. Output a single Python dictionary with exactly three keys: `\"rule\"`, `\"partition_1\"`, and `\"partition_3\"`.\n2. `\"rule\"` must be a string containing a valid Python `lambda` function. This function must take a single argument `team` (a list of 6 distinct integers from 1 to 24) and return a boolean (`True` if the team can cooperate, `False` otherwise).\n3. `\"partition_1\"` must be a list of 4 lists, representing a valid partition of the 24 students into four 6-person teams, such that exactly ONE team evaluates to `True` under your rule.\n4. `\"partition_3\"` must be a list of 4 lists, representing a valid partition of the 24 students into four 6-person teams, such that exactly THREE teams evaluate to `True` under your rule.\n5. Your rule must mathematically guarantee that for *any* valid partition of the 24 students into four 6-person teams, the number of cooperating teams is always exactly 1 or exactly 3.\n\nFormat:\n- Put ONLY the Python dictionary literal inside the `<construct>...</construct>` block.\n- Do not use markdown code fences around the dictionary.", "ref_construction": "{\n \"rule\": \"lambda team: sum(1 for x in team if x in {1, 2, 3}) % 2 == 1\",\n \"partition_1\": [\n [1, 2, 3, 4, 5, 6],\n [7, 8, 9, 10, 11, 12],\n [13, 14, 15, 16, 17, 18],\n [19, 20, 21, 22, 23, 24]\n ],\n \"partition_3\": [\n [1, 4, 5, 6, 7, 8],\n [2, 9, 10, 11, 12, 13],\n [3, 14, 15, 16, 17, 18],\n [19, 20, 21, 22, 23, 24]\n ]\n}", "verify_code": "import sys\nimport ast\nfrom itertools import combinations\nimport builtins\n\ndef verify():\n # Read full stdin\n input_str = sys.stdin.read().strip()\n if not input_str:\n print(\"Empty input\")\n return\n \n # Parse payload using ast.literal_eval\n try:\n data = ast.literal_eval(input_str)\n except Exception as e:\n print(f\"Parse error: {e}\")\n return\n \n if not isinstance(data, dict):\n print(\"Payload must be a dictionary\")\n return\n \n expected_keys = {\"rule\", \"partition_1\", \"partition_3\"}\n if set(data.keys()) != expected_keys:\n print(f\"Dictionary must contain exactly keys {expected_keys}\")\n return\n \n rule_str = data[\"rule\"]\n if not isinstance(rule_str, str):\n print(\"'rule' must be a string\")\n return\n \n # Evaluate the lambda function in a safe environment\n allowed_names = {'sum', 'len', 'set', 'list', 'tuple', 'any', 'all', 'min', 'max', 'abs', 'bool', 'int', 'map', 'filter'}\n safe_builtins = {k: getattr(builtins, k) for k in allowed_names if hasattr(builtins, k)}\n safe_env = {\"__builtins__\": safe_builtins}\n \n try:\n rule = eval(rule_str, safe_env, {})\n except Exception as e:\n print(f\"Error evaluating rule: {e}\")\n return\n \n if not callable(rule):\n print(\"'rule' must evaluate to a callable function\")\n return\n \n # Helper to validate partition structures\n def validate_partition(part, name):\n if not isinstance(part, list) or len(part) != 4:\n return False, f\"'{name}' must be a list of 4 lists\"\n seen = set()\n for team in part:\n if not isinstance(team, list) or len(team) != 6:\n return False, f\"Each team in '{name}' must be a list of 6 integers\"\n for student in team:\n if not isinstance(student, int) or student < 1 or student > 24:\n return False, f\"Students in '{name}' must be integers from 1 to 24\"\n if student in seen:\n return False, f\"Student {student} appears multiple times in '{name}'\"\n seen.add(student)\n if len(seen) != 24:\n return False, f\"'{name}' does not contain all 24 students\"\n return True, \"\"\n\n # Validate partition_1\n ok, msg = validate_partition(data[\"partition_1\"], \"partition_1\")\n if not ok:\n print(msg)\n return\n \n # Validate partition_3\n ok, msg = validate_partition(data[\"partition_3\"], \"partition_3\")\n if not ok:\n print(msg)\n return\n \n # Apply rule to partition_1 and verify exactly 1 True\n try:\n p1_evals = [bool(rule(list(team))) for team in data[\"partition_1\"]]\n except Exception as e:\n print(f\"Error applying rule to partition_1: {e}\")\n return\n \n if sum(p1_evals) != 1:\n print(f\"partition_1 must have exactly 1 cooperating team, got {sum(p1_evals)}\")\n return\n \n # Apply rule to partition_3 and verify exactly 3 True\n try:\n p3_evals = [bool(rule(list(team))) for team in data[\"partition_3\"]]\n except Exception as e:\n print(f\"Error applying rule to partition_3: {e}\")\n return\n \n if sum(p3_evals) != 3:\n print(f\"partition_3 must have exactly 3 cooperating teams, got {sum(p3_evals)}\")\n return\n\n # Mathematical verification of the universal property\n # Any rule that guarantees a constant sum modulo 2 over all partitions MUST be a degree-1 function.\n # We evaluate the rule on all 134,596 possible teams and verify it is of the form:\n # f(S) = sum_{x in S} w_x + C (mod 2)\n elements = list(range(1, 25))\n subsets = list(combinations(elements, 6))\n \n f_vals = {}\n try:\n for S in subsets:\n f_vals[S] = bool(rule(list(S)))\n except Exception as e:\n print(f\"Error applying rule to subset {S}: {e}\")\n return\n \n # Determine the weights w_x for each element\n w = {1: 0}\n for v in range(2, 25):\n # Pick a base set A containing 1 but not v\n if v > 6:\n A = (1, 2, 3, 4, 5, 6)\n else:\n A = (1, 7, 8, 9, 10, 11)\n A_minus_1_plus_v = tuple(sorted((set(A) - {1}) | {v}))\n w[v] = (f_vals[A] + f_vals[A_minus_1_plus_v]) % 2\n \n # Determine the constant C\n S0 = (1, 2, 3, 4, 5, 6)\n sum_w_S0 = sum(w[x] for x in S0) % 2\n C = (f_vals[S0] + sum_w_S0) % 2\n \n # Verify that the function exactly matches the degree-1 polynomial for ALL subsets\n for S in subsets:\n expected = (w[S[0]] + w[S[1]] + w[S[2]] + w[S[3]] + w[S[4]] + w[S[5]] + C) % 2\n if f_vals[S] != expected:\n print(\"Rule does not mathematically guarantee the universal property (not a degree-1 function).\")\n return\n \n # Verify that the sum over any partition is exactly 1 or 3\n # The sum over a partition modulo 2 is equivalent to the sum of all w_x modulo 2.\n sum_all_w = sum(w.values()) % 2\n if sum_all_w != 1:\n print(\"Rule guarantees a constant parity of cooperating teams, but the sum is not odd (so it cannot be exactly 1 or 3).\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "RMO-2018-P4", "category": "Existence and Construction", "id": "RMO-2018-P4-81", "query": "\"In an $n\\\\times n$ grid, some squares are painted black such that the bottom-left square $L$ and the top-right square $R$ are not painted black, and every possible path of a knight from $L$ to $R$ passes through at least one black square. Determine all integers $n\\\\geq4$ for which there must exist three diagonally adjacent squares, at least two of which are painted black.\n\"", "ref_answer": "All integers that are congruent to $1$ modulo $3$ and greater than $1$", "ref_solution": "The answer is all integers $n \\equiv 1 \\pmod 3$ with $n > 1$.\n\nNumber the rows from bottom to top and the columns from left to right consecutively as $1,2,\\dots,n$. Let the coordinates of the bottom-left square $L$ be $(1,1)$ and the top-right square $R$ be $(n,n)$.\n\n**Case 1: $n = 3k$**\nColor black all squares in rows whose numbers are congruent to $2 \\pmod 3$. \nIn this coloring, there is no set of three diagonally adjacent squares with at least two black squares, because out of any three consecutive rows, exactly one is congruent to $2 \\pmod 3$. \nIf a knight starts from $L(1,1)$ and does not pass through any black square, it can only move between the uncolored rows $y \\equiv 1 \\pmod 3$ and $y \\equiv 0 \\pmod 3$. A knight move from $y \\equiv 1 \\pmod 3$ must land in $y' \\equiv 0 \\pmod 3$, and vice versa. By checking the possible changes in coordinates, one can verify the invariant that for any reachable square $(x,y)$, $x \\equiv y \\pmod 2$ if $y \\equiv 1 \\pmod 3$, and $x \\not\\equiv y \\pmod 2$ if $y \\equiv 0 \\pmod 3$. Since $R=(3k, 3k)$ has $y \\equiv 0 \\pmod 3$ but $x \\equiv y \\pmod 2$, it violates the invariant and cannot be reached. Thus, this coloring satisfies all requirements.\n\n**Case 2: $n = 3k+2$**\nColor black all squares in rows whose numbers are congruent to $0 \\pmod 3$. \nAnalogous to the previous case, no three diagonally adjacent squares contain more than one black square. The uncolored rows are $y \\equiv 1 \\pmod 3$ and $y \\equiv 2 \\pmod 3$. The invariant for reachable squares becomes $x \\equiv y \\pmod 2$ for $y \\equiv 1 \\pmod 3$, and $x \\not\\equiv y \\pmod 2$ for $y \\equiv 2 \\pmod 3$. The square $R=(3k+2, 3k+2)$ has $y \\equiv 2 \\pmod 3$ but $x \\equiv y \\pmod 2$, so it is unreachable.\n\n**Case 3: $n = 3k+1$**\nWe prove by induction that the statement holds (i.e., no such coloring exists) when $n=3k+1$. It suffices to show that if the statement were false, there would exist a path for the knight from $L$ to $R$ containing no black squares, contradicting the hypothesis.\n\n*Base case $k=1$ ($n=4$):* By the contradiction assumption, the diagonally adjacent squares $(1,4), (2,3), (3,2)$ cannot contain two black squares. Thus $(2,3)$ and $(3,2)$ are not both black. Assume without loss of generality that $(2,3)$ is unpainted; then the path $L(1,1) \\rightarrow (2,3) \\rightarrow R(4,4)$ contains no black squares, a contradiction.\n\n*Inductive step:* Assume $k>1$ and that the statement holds for all smaller values of $k$; we consider the case $k$. For a square $(a,b)$, denote $(a',b')=(a+3k-3,\\;b+3k-3)$.\nBy the contradiction assumption, the squares $(2,3)$ and $(3,2)$ are not both black; assume without loss of generality that $(2,3)$ is unpainted. \nIf the square $(2',3')$ is also unpainted, then by the induction hypothesis (applied to the $(3k-2) \\times (3k-2)$ subgrid from $(2,3)$ to $(2',3')$) there exists a path from $(2,3)$ to $(2',3')$ containing no black squares. Consequently, the path $L \\rightarrow (2,3) \\rightarrow \\dots \\rightarrow (2',3') \\rightarrow R$ contains no black squares.\n\nIf the square $(2',3')$ is painted black, then by the contradiction assumption the square $(3',2')$ is unpainted. To block the symmetric unpainted path $L \\rightarrow (3,2) \\rightarrow \\dots \\rightarrow (3',2') \\rightarrow R$, we may assume that $(3,2)$ is painted black. \nFurthermore, if $(4,4)$ were unpainted, the induction hypothesis applied to the subgrid from $(4,4)$ to $(4',4')$ would yield an unpainted path from $(4,4)$ to $R=(4',4')$, creating the unpainted path $L \\rightarrow (2,3) \\rightarrow (4,4) \\rightarrow \\dots \\rightarrow R$. Thus, we may assume the square $(4,4)$ is painted black. Similarly, to block the path $L \\rightarrow \\dots \\rightarrow (1',1') \\rightarrow (3',2') \\rightarrow R$, we may assume the square $(1',1')$ is painted black.\n\nBy the contradiction assumption, any three consecutive squares on a diagonal can contain at most one black square. Thus, the black squares $(3,2)$ and $(4,4)$ force their diagonally adjacent squares to be unpainted. This ensures that the knight can go from $L$ to the square $(1,4)$ entirely via forced unpainted squares (e.g., $L \\rightarrow (2,3) \\rightarrow (3,5) \\rightarrow (1,4)$). Similarly, the black squares $(1',1')$ and $(2',3')$ force a sequence of their diagonal neighbors to be unpainted, providing an unpainted path from $(1',4')$ to $R$. \n\nFinally, by the induction hypothesis applied to the $(3k-2) \\times (3k-2)$ subgrid from $(1,4)$ to $(1',4')$, the knight can travel from $(1,4)$ to $(1',4')$ without landing on any black squares. Concatenating these segments yields a valid knight path from $L$ to $R$ with no black squares, which completes the induction and establishes the contradiction.", "grading_guidelines": "(Partial) 1. For n≡0 or 2 (mod 3), gave an explicit coloring (e.g. all squares in one residue class of rows mod 3) and correctly argued that it blocks all knight paths from L to R. 2. Proved the “no forced triple” property for the construction: in any three diagonally adjacent squares, at most one can be black (e.g. because among three consecutive rows exactly one is a black row). 3. Established a correct invariant for knight moves restricted to the unpainted rows (typically combining y mod 3 with x≡y (mod 2) / x≢y (mod 2)) and used it to show R is unreachable under the proposed construction. (Almost) 1. Correctly proved the positive direction for n≡1 (mod 3) by induction/reduction to a smaller subgrid, but left a localized gap in one of the forced-unpainted path concatenations near the boundary (e.g. reaching (1,4) or (1',4') without hitting black squares). 2. Solved the base case n=4 and set up the inductive step for n=3k+1, including the necessary WLOG choices (e.g. assuming (2,3) unpainted, then considering (2',3') black/unpainted), but did not fully justify one of the “to block the symmetric path, we may assume … is black” implications. 3. Completed all three cases and obtained the correct answer set, but made a minor non-negligible mistake in one congruence/invariant check (e.g. the parity condition at R in Case 1/2) while the overall method is clearly correct.", "instruction": "For the specific case $n=81$, provide an explicit construction of the grid coloring that satisfies all the problem's conditions (i.e., $L$ and $R$ are white, every knight path from $L$ to $R$ contains at least one black square, and no three diagonally adjacent squares have two or more black squares).\n\nConstruction requirements:\n- Output a single Python expression that evaluates to a list of lists of integers, representing the $81 \\times 81$ grid.\n- Use `0` for white squares and `1` for black squares.\n- The outer list should contain 81 inner lists (rows), ordered from top to bottom. Each inner list should contain 81 integers representing the columns from left to right.\n- The expression must be self-contained and evaluate directly to the target data structure when passed to `eval()`.\n- You may use list comprehensions, conditional expressions, and integer constants. Do not use assignment statements, imports, or any non-expression syntax.\n- Put ONLY the raw Python expression inside the construction block. Do not wrap it in markdown code blocks or add any other text.", "ref_construction": "[[1 if i % 3 == 1 else 0 for j in range(81)] for i in range(81)]", "verify_code": "import sys\nfrom collections import deque\n\ndef verify():\n raw_input = sys.stdin.read().strip()\n if not raw_input:\n print(\"Empty input.\")\n return\n \n try:\n # The instruction allows list comprehensions, so we use eval instead of ast.literal_eval\n grid = eval(raw_input)\n except Exception as e:\n print(f\"Failed to parse input: {e}\")\n return\n \n # 2. Verify grid dimensions and elements\n if not isinstance(grid, list):\n print(\"Grid must be a list.\")\n return\n if len(grid) != 81:\n print(f\"Grid must have exactly 81 rows, got {len(grid)}.\")\n return\n \n for r_idx, row in enumerate(grid):\n if not isinstance(row, list):\n print(f\"Row {r_idx} is not a list.\")\n return\n if len(row) != 81:\n print(f\"Row {r_idx} must have exactly 81 elements, got {len(row)}.\")\n return\n for c_idx, val in enumerate(row):\n if type(val) is not int or val not in (0, 1):\n print(f\"Element at ({r_idx}, {c_idx}) is not strictly the integer 0 or 1.\")\n return\n \n # 3. Verify L and R are 0\n if grid[80][0] != 0:\n print(\"Bottom-left square (80, 0) must be 0 (white).\")\n return\n if grid[0][80] != 0:\n print(\"Top-right square (0, 80) must be 0 (white).\")\n return\n \n # 4. Iterate through all valid starting positions for a diagonal of length 3\n # Main diagonals\n for r in range(79):\n for c in range(79):\n count = grid[r][c] + grid[r+1][c+1] + grid[r+2][c+2]\n if count >= 2:\n print(f\"Main diagonal starting at ({r}, {c}) has {count} black squares (must be strictly less than 2).\")\n return\n \n # Anti-diagonals\n for r in range(79):\n for c in range(2, 81):\n count = grid[r][c] + grid[r+1][c-1] + grid[r+2][c-2]\n if count >= 2:\n print(f\"Anti-diagonal starting at ({r}, {c}) has {count} black squares (must be strictly less than 2).\")\n return\n \n # 5. Initialize a BFS queue to find all reachable squares from (80, 0) using valid knight moves\n queue = deque([(80, 0)])\n visited = {(80, 0)}\n \n knight_moves = [\n (-2, -1), (-2, 1), (-1, -2), (-1, 2),\n (1, -2), (1, 2), (2, -1), (2, 1)\n ]\n \n while queue:\n r, c = queue.popleft()\n \n # 6. Assert that the top-right square (0, 80) is not reachable\n if (r, c) == (0, 80):\n print(\"Top-right square (0, 80) is reachable from bottom-left square without hitting a black square.\")\n return\n \n for dr, dc in knight_moves:\n nr, nc = r + dr, c + dc\n if 0 <= nr < 81 and 0 <= nc < 81:\n if (nr, nc) not in visited:\n # Restricted only to squares where grid[r][c] == 0\n if grid[nr][nc] == 0:\n visited.add((nr, nc))\n queue.append((nr, nc))\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "RMO-2017-P22", "category": "Extremal Problems", "id": "RMO-2017-P22", "query": "On a $200\\\\times200$ chessboard, some squares contain a red or blue piece, while the remaining squares are empty. Two pieces are said to \\\"see\\\" each other if they are in the same row or the same column. Suppose each piece sees exactly five pieces of the opposite color (and may also see some pieces of the same color). Find the maximum possible total number of pieces on the chessboard.", "ref_answer": "3800", "ref_solution": "The maximum possible total number of pieces on the chessboard is 3800.\n\nThere exists a valid placement of pieces that satisfies the requirements, yielding a total of $10\\times190\\times2=3800$ pieces.\n\nNote that when a row contains pieces of only one colour, the row can have at most $200$ pieces. When a row contains pieces of two colours, each colour appears at most $5$ times, so the row can have at most $10$ pieces. If there are $191$ rows that contain two colours, then the total number of pieces does not exceed $9\\times200+191\\times10=3710<3800$. Suppose at most $190$ rows contain two colours; similarly, we may assume at most $190$ columns contain two colours. \n\nConsider the number $S$ of pairs of pieces of different colours that lie in the same row or the same column. On the one hand, if a row contains only one colour, it contributes no heterochromatic pairs; if a row contains two colours, the number of heterochromatic pairs in that row is at most $5\\times5=25$. The same holds for columns. Hence, $S\\le 25\\times190\\times2$. On the other hand, each piece forms heterochromatic pairs with exactly $5$ other pieces, so the total number of pieces is at most $\\frac{2S}{5}\\le \\frac{2 \\times (25 \\times 190 \\times 2)}{5} = 3800$.", "grading_guidelines": "(Partial) 1. Observed that any row (or column) containing both colours has at most 10 pieces (at most 5 of each colour), since each piece must see exactly five opposite-colour pieces in its row/column. 2. Introduced the double-counting parameter S = number of opposite-colour pairs in a common row or column, and correctly deduced that the total number of pieces equals 2S/5. 3. Obtained a nontrivial global upper bound by combining a bound on heterochromatic pairs per mixed row/column (e.g. ≤25) with a bound on the number of mixed rows/columns (e.g. ≤200), even if the final numeric maximum is not reached. (Almost) 1. Proved the upper bound 3800 via the S double count, but made a small slip in justifying that one may assume at most 190 mixed rows and at most 190 mixed columns (or handled only rows but not columns), while the rest of the argument is correct. 2. Gave a construction intended to achieve 3800 pieces (with 190 mixed rows and 190 mixed columns, 5 of each colour in each mixed line), but did not fully verify the condition “each piece sees exactly five opposite-colour pieces” for all pieces (e.g. missed checking edge rows/columns or symmetry cases). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Provide an explicit construction of the chessboard that achieves this maximum possible total number of pieces.\n\nConstruction requirements:\n- Output a single Python expression that evaluates to a 200x200 list of lists of integers representing the chessboard.\n- Use 1 for a red piece, 2 for a blue piece, and 0 for an empty square.\n- The configuration must satisfy all problem constraints: every piece (1 or 2) must share its row and column with exactly 5 pieces in total of the opposite color.\n- The total number of pieces (1s and 2s) must be maximized.\n- The output must be a pure Python expression (e.g., using list comprehensions and conditional expressions). Do not include any explanations, comments, variable assignments, or markdown formatting (such as ```python). Put ONLY the raw Python expression inside the construction block.", "ref_construction": "[[1 if (r < 5 and c >= 10) or (c < 5 and r >= 10) else 2 if (5 <= r < 10 and c >= 10) or (5 <= c < 10 and r >= 10) else 0 for c in range(200)] for r in range(200)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n \n try:\n # The instruction allows pure Python expressions including list comprehensions,\n # so we use eval() as specified in the user intent.\n board = eval(payload)\n except Exception as e:\n print(f\"Failed to evaluate python expression: {e}\")\n return\n \n if type(board) is not list or len(board) != 200:\n print(\"Board must be a list of exactly 200 elements.\")\n return\n \n for r, row in enumerate(board):\n if type(row) is not list or len(row) != 200:\n print(f\"Row {r} is not a list of exactly 200 elements.\")\n return\n for c, val in enumerate(row):\n if type(val) is not int or val not in {0, 1, 2}:\n print(f\"Invalid value {repr(val)} at ({r}, {c}). Expected 0, 1, or 2.\")\n return\n \n total_pieces = 0\n row_counts = {1: [0]*200, 2: [0]*200}\n col_counts = {1: [0]*200, 2: [0]*200}\n \n # Count pieces and precompute the number of 1s and 2s in each row and column\n for r in range(200):\n for c in range(200):\n val = board[r][c]\n if val in {1, 2}:\n total_pieces += 1\n row_counts[val][r] += 1\n col_counts[val][c] += 1\n \n if total_pieces != 3800:\n print(f\"Total pieces is {total_pieces}, expected exactly 3800.\")\n return\n \n # Verify that each piece sees exactly 5 pieces of the opposite color\n for r in range(200):\n for c in range(200):\n val = board[r][c]\n if val in {1, 2}:\n opp = 3 - val\n sees = row_counts[opp][r] + col_counts[opp][c]\n if sees != 5:\n print(f\"Piece at ({r}, {c}) of color {val} sees {sees} opposite color pieces in its row and column combined, expected exactly 5.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "RMO-2009-P7", "category": "Extremal Problems", "id": "RMO-2009-P7", "query": "\"On a chessboard, the eight squares on a diagonal are called a fence. A rook starts moving from a square outside the fence. In each move, it goes from one square to another, satisfying: (1) It cannot move onto the fence; (2) Each square is moved to at most once. Find the maximum number of moves that cross the fence.\n\"", "ref_answer": "47", "ref_solution": "The answer is $47$.\n\nLet the square in row $i$ and column $j$ be denoted by $(i,j)$. The fence consists of the eight squares $(i,i)$ for $1\\le i\\le 8$. We divide the remaining squares into four classes:\n\\[\n\\begin{aligned}\nA&=\\{(i,j):2\\le j+1\\le i\\le 4\\}\\cup\\{(i,j):5\\le j\\le i-1\\le 7\\},\\\\\nB&=\\{(i,j):2\\le i+1\\le j\\le 4\\}\\cup\\{(i,j):5\\le i\\le j-1\\le 7\\},\\\\\nC&=\\{(i,j):5\\le i\\le 8,\\ 1\\le j\\le 4\\},\\\\\nD&=\\{(i,j):1\\le i\\le 4,\\ 5\\le j\\le 8\\}.\n\\end{aligned}\n\\]\nThus $A$ and $C$ are below the fence, while $B$ and $D$ are above the fence. Also $|A|=|B|=12$, so $|A\\cup B|=24$.\n\nA rook move crosses the fence exactly when its two endpoints lie on opposite sides of the main diagonal. With the above coloring, every crossing is of one of the following two types:\n\\[\nA\\leftrightarrow D \\qquad\\text{or}\\qquad B\\leftrightarrow C.\n\\]\nIndeed, a horizontal or vertical segment crossing the diagonal in the top-left or bottom-right part of the board has its near-diagonal endpoint in $A$ or $B$, and the other endpoint in $D$ or $C$ respectively.\n\nTherefore every crossing has one endpoint in $A\\cup B$. Since the rook never visits a square more than once, any fixed square in $A\\cup B$ can be an endpoint of at most two crossing moves: one when the rook enters the square and one when it leaves. Hence the total number of crossings is at most\n\\[\n2|A\\cup B|=48.\n\\]\n\nWe now rule out equality. Suppose that $48$ crossings were possible. Then every square in $A\\cup B$ would have to be used as an endpoint of exactly two crossing moves. In particular, no square in $A\\cup B$ could be incident to a non-crossing move in the rook's path.\n\nConsequently, once the path uses crossings of type $A\\leftrightarrow D$, it cannot switch to crossings of type $B\\leftrightarrow C$ through a non-crossing move involving $A$ or $B$. The only possible switch would have to pass between a square in $C$ and a square in $D$ without using $A$ or $B$. But this is impossible: squares of $C$ have rows $5,6,7,8$ and columns $1,2,3,4$, while squares of $D$ have rows $1,2,3,4$ and columns $5,6,7,8$, so no rook move can go directly from $C$ to $D$.\n\nThus, under the equality assumption, all crossings would have to be of a single type. If all crossings are of type $A\\leftrightarrow D$, then only the $12$ squares of $A$ can serve as the required near-diagonal endpoints, giving at most $2|A|=24$ crossings. Similarly, if all crossings are of type $B\\leftrightarrow C$, there are at most $2|B|=24$ crossings. This contradicts the assumption of $48$ crossings. Hence at most $47$ crossings are possible.\n\nIt remains to show that $47$ crossings can be achieved. The following sequence of visited squares does so:\n\\[\n\\begin{aligned}\n&(8,2)\\to(1,2)\\to(7,2)\\to(7,8)\\to(7,3)\\to(1,3)\\to(8,3)\\to(2,3)\\\\\n&\\to(6,3)\\to(6,8)\\to(6,2)\\to(6,7)\\to(6,4)\\to(1,4)\\to(8,4)\\to(2,4)\\\\\n&\\to(7,4)\\to(3,4)\\to(5,4)\\to(5,8)\\to(5,3)\\to(5,7)\\to(5,2)\\to(5,6)\\\\\n&\\to(8,6)\\to(1,6)\\to(7,6)\\to(2,6)\\to(2,1)\\to(2,7)\\to(8,7)\\to(3,7)\\\\\n&\\to(3,1)\\to(3,6)\\to(3,2)\\to(3,5)\\to(8,5)\\to(2,5)\\to(7,5)\\to(1,5)\\\\\n&\\to(6,5)\\to(4,5)\\to(4,1)\\to(4,6)\\to(4,2)\\to(4,7)\\to(4,3)\\to(4,8).\n\\end{aligned}\n\\]\nEach listed square is off the fence, no square is repeated, and each consecutive pair lies in a common row or column. Moreover, for every consecutive pair, the two endpoints lie on opposite sides of the main diagonal, so every one of the $47$ moves crosses the fence. Therefore the maximum number of crossings is exactly $47$.", "grading_guidelines": "(Partial) 1. Observed/proved that a rook move crosses the fence iff its endpoints lie on opposite sides of the main diagonal (equivalently, one has i<j and the other i>j), since the rook moves horizontally/vertically and cannot land on the diagonal. 2. Established a global upper bound of the form “#crossings ≤ 48” by identifying a set of 24 off-diagonal squares near the fence (e.g. A∪B in the official partition) such that every crossing has an endpoint in this set, and arguing each such square can be an endpoint of at most two crossing moves (enter/leave) because squares are not revisited. 3. Gave an explicit long non-repeating rook path avoiding the fence that realizes at least 40 crossing moves (or, more generally, a concrete construction with a stated number of crossings and a verifiable check that every move crosses). (Almost) 1. Proved the upper bound 48 using the “each crossing uses A∪B, hence ≤2|A∪B|” endpoint-counting argument, and attempted to rule out equality by a switching/connectedness argument, but left a small gap in justifying why a 48-crossing path cannot mix the two crossing types (A↔D and B↔C). 2. Correctly proved that 48 is impossible (hence the maximum is ≤47), but did not supply a complete explicit path achieving 47, or gave a construction that is off by one move / has one repeated square / has one move that does not cross. 3. Presented a construction intended to achieve 47 crossings and verified legality (no fence, no repeats, rook moves), but did not fully check that every consecutive pair lies on opposite sides of the diagonal (or missed a boundary case where a move would cross through a fence square without landing on it).", "instruction": "Provide an explicit construction for the sequence of squares visited by the rook to achieve the maximum possible number of moves that cross the fence.\n\nConstruction format requirements:\n- Output a single Python list of lists, where each inner list represents a square as `[r, c]`.\n- Use 0-based indexing for the 8x8 chessboard, so `0 <= r <= 7` and `0 <= c <= 7`.\n- The fence is defined as the main diagonal where `r == c`.\n- The sequence must start with the initial square and contain all subsequently visited squares in order.\n- The rook cannot move onto the fence (i.e., no square in the sequence can have `r == c`).\n- Each square can be visited at most once.\n- Every move must be a valid rook move (either `r` or `c` remains constant, and the other strictly changes).\n- To maximize efficiency in your output, every move in your sequence must strictly cross the fence. A move from `[r1, c1]` to `[r2, c2]` crosses the fence if `(r1 - c1) * (r2 - c2) < 0`.\n- The sequence must achieve the maximum possible number of fence-crossing moves for this board.\n- Put ONLY the Python literal list of lists inside the `<construct>` block.", "ref_construction": "[[7, 1], [0, 1], [6, 1], [6, 7], [6, 2], [0, 2], [7, 2], [1, 2], [5, 2], [5, 7], [5, 1], [5, 6], [5, 3], [0, 3], [7, 3], [1, 3], [6, 3], [2, 3], [4, 3], [4, 7], [4, 1], [4, 6], [4, 2], [4, 5], [7, 5], [0, 5], [6, 5], [1, 5], [1, 0], [1, 6], [7, 6], [2, 6], [2, 0], [2, 5], [2, 1], [2, 4], [7, 4], [1, 4], [6, 4], [0, 4], [5, 4], [3, 4], [3, 0], [3, 5], [3, 1], [3, 6], [3, 2], [3, 7]]", "verify_code": "import sys\nimport ast\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n \n try:\n points = ast.literal_eval(payload)\n except Exception as e:\n print(f\"Failed to parse input as Python literal: {e}\")\n return\n \n if not isinstance(points, list):\n print(\"The construction must be a list.\")\n return\n \n if len(points) != 48:\n print(f\"Expected exactly 48 points, got {len(points)}.\")\n return\n \n seen = set()\n for i, pt in enumerate(points):\n if not isinstance(pt, (list, tuple)):\n print(f\"Point at index {i} is not a list or tuple.\")\n return\n if len(pt) != 2:\n print(f\"Point at index {i} does not have exactly 2 elements.\")\n return\n \n r, c = pt\n if type(r) is not int or type(c) is not int:\n print(f\"Coordinates of point at index {i} are not strictly integers.\")\n return\n \n if not (0 <= r <= 7 and 0 <= c <= 7):\n print(f\"Coordinates of point {pt} at index {i} are out of bounds (0-7).\")\n return\n \n if r == c:\n print(f\"Point {pt} at index {i} lies on the fence (r == c).\")\n return\n \n tup = (r, c)\n if tup in seen:\n print(f\"Point {pt} at index {i} is visited more than once.\")\n return\n seen.add(tup)\n \n for i in range(len(points) - 1):\n r1, c1 = points[i]\n r2, c2 = points[i+1]\n \n # Check valid rook move\n if not ((r1 == r2 and c1 != c2) or (c1 == c2 and r1 != r2)):\n print(f\"Move from {points[i]} to {points[i+1]} is not a valid rook move.\")\n return\n \n # Check fence crossing\n if (r1 - c1) * (r2 - c2) >= 0:\n print(f\"Move from {points[i]} to {points[i+1]} does not strictly cross the fence.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "RMO-2009-P22", "category": "Extremal Problems", "id": "RMO-2009-P22", "query": "On a $10\\\\times10$ chessboard there are $k$ rooks. A square that can be attacked by at least one rook is called dangerous (including the square where a rook is located). If after removing any one rook, at least one dangerous square becomes not dangerous, determine the maximum possible value of $k$.", "ref_answer": "16", "ref_solution": "First, we prove that $k \\le 16$. \nSuppose that every row contains at least one rook. Then all squares on the board are dangerous. If some row contains at least two rooks, removing one of them leaves every row with at least one rook, meaning all squares are still dangerous, which contradicts the problem condition. Hence, each row must contain exactly one rook, yielding $k=10$. By symmetry, if every column contains at least one rook, we also have $k=10$.\n\nNow assume there is at least one row and at least one column without a rook. \nFor each rook, it must be the unique rook in its row or the unique rook in its column; otherwise, removing it would leave at least one rook in its row and at least one rook in its column, meaning no dangerous square would become safe. \nWe associate each rook with a row or column in which it is the unique rook. \nLet $R$ be the set of rows containing exactly one rook, and $C$ be the set of columns containing exactly one rook. Since every rook is associated with a row in $R$ or a column in $C$, we have $k \\le |R| + |C|$. \n\nSince there is at least one empty row, $|R| \\le 9$. If $|R| = 9$, then exactly 9 rows contain exactly one rook, and the remaining row is empty. This implies the total number of rooks on the board is exactly 9, so $k=9$. By symmetry, if $|C| = 9$, then $k=9$. \nOtherwise, we must have $|R| \\le 8$ and $|C| \\le 8$. It follows that the total number of rooks is bounded by $k \\le |R| + |C| \\le 8 + 8 = 16$.\n\nFinally, we construct an example with $k=16$. Let the squares occupied by the 16 rooks be $(1,i)$ and $(i,1)$ for $i=2,3,\\dots,9$. \nIn this configuration, after removing the rook from square $(1,i)$, the square $(10,i)$ changes from dangerous to safe (since row 10 is empty and the only rook in column $i$ was at $(1,i)$). \nSimilarly, after removing the rook from square $(i,1)$, the square $(i,10)$ changes from dangerous to safe. \nThis configuration satisfies the problem's requirement. Therefore, the maximum possible value of $k$ is $16$.", "grading_guidelines": "(Partial) 1. Observed the key necessity: for every rook, it must be the unique rook in its row or the unique rook in its column (otherwise removing it leaves its whole row and column still dangerous, so nothing changes). 2. Derived an upper bound of the form k ≤ |R|+|C| where R is the set of rows with exactly one rook and C is the set of columns with exactly one rook, by assigning each rook to one such unique row/column. 3. Gave a concrete configuration with 16 rooks (e.g. on (1,i) and (i,1) for i=2,…,9) and correctly argued that removing any rook makes at least one previously dangerous square safe. (Almost) 1. Proved the upper bound k ≤ 16 via the |R|+|C| argument, but did not handle the special subcase “all rows occupied” or “all columns occupied” correctly (or omitted it), leaving a small logical gap. 2. Found the correct extremal configuration with k=16 and checked the condition for most rooks, but missed/incorrectly justified one boundary square becoming safe after deletion (e.g. the need for an empty row/column in the witness square). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Provide an explicit construction for the maximum possible value of $k$.\n\nConstruction requirements:\n- Output a single Python expression (e.g., a list comprehension) that evaluates to a 10x10 matrix (a list of 10 lists, each containing 10 integers).\n- The matrix should contain only 0s and 1s, where 1 represents a rook and 0 represents an empty square.\n- The configuration must satisfy the problem constraint: for every rook, there must be at least one square (which could be its own square) that is attacked ONLY by this rook.\n- The number of rooks $k$ (i.e., the number of 1s in the matrix) must be exactly the maximum possible value.\n- Put ONLY the Python expression inside the construction block, without any additional text, markdown, or code fences.", "ref_construction": "[[1 if (r == 1 and c >= 2) or (c == 1 and r >= 2) else 0 for c in range(10)] for r in range(10)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n \n try:\n # Evaluate the payload as a Python expression (e.g., list comprehension)\n matrix = eval(payload)\n except Exception as e:\n print(f\"Failed to evaluate python expression: {e}\")\n return\n\n if type(matrix) is not list:\n print(\"Matrix must be a list.\")\n return\n \n if len(matrix) != 10:\n print(f\"Matrix must have exactly 10 rows, got {len(matrix)}.\")\n return\n \n for i, row in enumerate(matrix):\n if type(row) is not list:\n print(f\"Row {i} is not a list.\")\n return\n if len(row) != 10:\n print(f\"Row {i} must have exactly 10 elements, got {len(row)}.\")\n return\n for j, val in enumerate(row):\n if type(val) is not int or val not in (0, 1):\n print(f\"Element at ({i}, {j}) is not 0 or 1.\")\n return\n\n rooks = []\n for r in range(10):\n for c in range(10):\n if matrix[r][c] == 1:\n rooks.append((r, c))\n \n if len(rooks) != 16:\n print(f\"Expected exactly 16 rooks, got {len(rooks)}.\")\n return\n\n # Count the number of rooks in each row and column\n row_counts = [0] * 10\n col_counts = [0] * 10\n for r, c in rooks:\n row_counts[r] += 1\n col_counts[c] += 1\n \n # Calculate how many rooks attack each square (r, c)\n attack_counts = [[0]*10 for _ in range(10)]\n for r in range(10):\n for c in range(10):\n # A rook at (r, c) would be counted twice (once in row_counts, once in col_counts)\n attack_counts[r][c] = row_counts[r] + col_counts[c] - matrix[r][c]\n\n # Verify that every rook has at least one uniquely attacked square\n for rr, cc in rooks:\n has_unique = False\n \n # Check all squares in the same column\n for r in range(10):\n if attack_counts[r][cc] == 1:\n has_unique = True\n break\n \n if has_unique:\n continue\n \n # Check all squares in the same row\n for c in range(10):\n if attack_counts[rr][c] == 1:\n has_unique = True\n break\n \n if not has_unique:\n print(f\"Rook at ({rr}, {cc}) does not have any uniquely attacked square.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "ELMO-2021-P3", "category": "Extremal Problems", "id": "ELMO-2021-P3", "query": "\"A $100\\\\times100$ grid is colored using $101$ colors. A cell is called \\\"\"colorful\\\"\" if in its row and column (a total of $199$ cells), each of the $101$ colors appears at least once. Find the maximum possible number of colorful cells.\n\"", "ref_answer": "9996.", "ref_solution": "We claim that the maximum possible number of colorful cells is $9996$.\n\nWe first provide a construction achieving $9996$ colorful cells. For $1\\le i\\le 101$, filling a cell with $i$ means coloring that cell with the $i$-th color. Consider the following coloring of the $100 \\times 100$ grid:\n$$\n\\begin{array}{|c|c|c|c|c|c|}\n\\hline\n4 & 5 & \\cdots & 101 & 3 & 2 \\\\\n\\hline\n5 & 6 & \\cdots & 4 & 3 & 2 \\\\\n\\hline\n\\vdots & \\vdots & \\ddots & \\vdots & \\vdots & \\vdots \\\\\n\\hline\n101 & 4 & \\cdots & 100 & 3 & 2 \\\\\n\\hline\n3 & 3 & \\cdots & 3 & 1 & 2 \\\\\n\\hline\n1 & 1 & \\cdots & 1 & 2 & 1 \\\\\n\\hline\n\\end{array}\n$$\nIn this table, the upper-left $98\\times 98$ square is colored cyclically with colors $4, 5, \\dots, 101$. It is easy to verify that, except for the $4$ cells in the lower-right $2\\times 2$ square (which only see colors $1, 2,$ and $3$ in their rows and columns), the remaining $9996$ cells are colorful. Thus, $9996$ colorful cells are attainable.\n\nNow we prove that $9996$ is the maximum. We consider two cases based on the frequencies of the colors used.\n\n**Case 1:** A certain color appears at most $98$ times.\nIf a color appears at most $98$ times, it can occupy at most $98$ rows and $98$ columns. Thus, there must exist at least two rows and two columns that contain no cell of that color. The four cells at the intersection of these rows and columns are then not colorful, because neither their row nor their column contains this color. Therefore, the number of colorful cells is at most $100^2 - 4 = 9996$.\n\n**Case 2:** Each color appears at least $99$ times.\nBecause there are $101$ colors and $100^2 = 101 \\times 99 + 1$ cells, there must be exactly $100$ colors that appear exactly $99$ times, and one color that appears exactly $100$ times. Denote the color appearing $100$ times by color $101$. We will prove that in this case, the number of colorful cells does not exceed $9900$.\n\nSuppose for the sake of contradiction that at most $99$ cells are not colorful. Since there are $100$ rows and $100$ columns, there must exist at least one row and at least one column that consist entirely of colorful cells. By permuting the rows and columns, we may assume that row $100$ and column $100$ consist entirely of colorful cells, so that all non-colorful cells lie inside the $99 \\times 99$ square in the upper-left corner. \n\nFor each $1 \\le i \\le 100$, color $i$ appears exactly $99$ times in the grid. Thus, there must be at least one column that contains no cell of color $i$. Since every cell in row $100$ is colorful, the cell in row $100$ of this column must still see color $i$ in either its row or its column. Because its column lacks color $i$, row $100$ must contain color $i$. This holds for all $i \\in \\{1, 2, \\dots, 100\\}$. Consequently, row $100$ contains all $100$ colors from $1$ to $100$. Since row $100$ has exactly $100$ cells, it cannot contain any cell of color $101$. \n\nBy symmetric reasoning, for each $1 \\le i \\le 100$, there must be a row that contains no cell of color $i$. Since every cell in column $100$ is colorful, column $100$ must contain color $i$. Thus, column $100$ also contains all colors from $1$ to $100$, and consequently contains no cell of color $101$.\n\nFinally, consider the cell at the intersection of row $100$ and column $100$. Neither its row nor its column contains color $101$. Thus, this cell is not colorful, which contradicts our assumption that row $100$ and column $100$ consist entirely of colorful cells. \n\nTherefore, our assumption was false, and there must be at least $100$ non-colorful cells. Hence, the number of colorful cells is at most $10000 - 100 = 9900 \\le 9996$.\n\nIn all cases, the maximum possible number of colorful cells is $9996$.", "grading_guidelines": "(Partial) 1. Gave a construction with at least 9996 colorful cells (e.g. a cyclic 98×98 block using 98 colors plus a completion), with a correct explanation that only 4 specified cells fail to be colorful. 2. Proved the key upper-bound lemma: if some color appears at most 98 times, then there exist two rows and two columns missing this color, hence at least 4 cells are not colorful and the number of colorful cells is at most 9996. 3. In the complementary frequency case, correctly derived the count constraint: if every color appears at least 99 times, then exactly one color appears 100 times and the other 100 colors appear 99 times each. (Almost) 1. Proved the upper bound 9996 in Case 1 (a color used ≤98 times) and correctly set up Case 2 (all colors used ≥99 times), but did not complete the Case 2 contradiction (e.g. failed to force a row/column with all colors 1–100 and hence no 101). 2. Completed both cases to obtain the bound 9996, but the proof that “if fewer than 100 non-colorful cells then there is a fully colorful row and a fully colorful column” is not fully justified or mishandles a boundary case. 3. Gave a correct construction achieving 9996 and the correct overall strategy for the upper bound, but left a localized gap (such as not rigorously arguing why row 100/column 100 cannot contain color 101, or not justifying the needed row/column permutations).", "instruction": "Construct a $100 \\times 100$ grid of integers representing the colors.\n\nConstruction requirements:\n- The grid must be a list of lists of integers.\n- Use colors $1, 2, \\dots, 101$.\n- The grid must find the maximum possible number of colorful cells. A cell $(r, c)$ is colorful if the union of colors in row $r$ and column $c$ contains all 101 colors.\n- Provide the answer as a single valid Python expression (using list comprehensions) that evaluates to the matrix. Do not list all 10,000 numbers explicitly; use logic to generate them.\n- Put ONLY the Python expression inside the construction block.Output formatting requirements:\n- Include exactly one construction block and put ONLY the JSON object between the tags:\n<construct>\n<json_object>\n</construct>\n- Do not use code fences. Do not put any extra text inside <construct>...</construct>.", "ref_construction": "[\n [\n ((r + c) % 98 + 4) if c < 98 else (3 if c == 98 else 2)\n for c in range(100)\n ]\n if r < 98 else\n (\n [3 if c < 98 else (1 if c == 98 else 2) for c in range(100)]\n if r == 98 else\n [1 if c < 98 else (2 if c == 98 else 1) for c in range(100)]\n )\n for r in range(100)\n]", "verify_code": "import sys\n\ndef verify():\n # Read the raw content from stdin.\n # The instruction guarantees the input is a Python expression.\n content = sys.stdin.read().strip()\n \n if not content:\n print(\"Error: Input is empty.\")\n return\n\n # Evaluate the string as a Python expression.\n # We use eval() because the instruction allows list comprehensions,\n # which ast.literal_eval() does not support.\n try:\n # We allow standard builtins (e.g., range, list) as they are needed for comprehensions.\n grid = eval(content, {\"__builtins__\": __builtins__})\n except SyntaxError:\n print(\"Error: Input is not a valid Python expression.\")\n return\n except Exception as e:\n print(f\"Error: Failed to evaluate expression. {e}\")\n return\n\n # Validate outer structure (List of Lists)\n if not isinstance(grid, list):\n print(\"Error: The evaluated object is not a list.\")\n return\n \n if len(grid) != 100:\n print(f\"Error: Grid must have exactly 100 rows, found {len(grid)}.\")\n return\n\n # Validate inner structure and values, and precompute row sets\n row_sets = []\n \n for r_idx, row in enumerate(grid):\n if not isinstance(row, list):\n print(f\"Error: Row {r_idx} is not a list.\")\n return\n if len(row) != 100:\n print(f\"Error: Row {r_idx} must have exactly 100 columns, found {len(row)}.\")\n return\n \n current_row_set = set()\n for c_idx, val in enumerate(row):\n if not isinstance(val, int):\n print(f\"Error: Cell ({r_idx}, {c_idx}) is not an integer.\")\n return\n if not (1 <= val <= 101):\n print(f\"Error: Cell ({r_idx}, {c_idx}) value {val} is out of valid range [1, 101].\")\n return\n current_row_set.add(val)\n row_sets.append(current_row_set)\n\n # Precompute column sets\n col_sets = []\n for c_idx in range(100):\n current_col_set = set()\n for r_idx in range(100):\n current_col_set.add(grid[r_idx][c_idx])\n col_sets.append(current_col_set)\n\n # Count \"colorful\" cells\n # A cell (r, c) is colorful if the union of colors in row r and column c contains all 101 colors.\n colorful_count = 0\n target_colors = 101\n\n for r in range(100):\n r_set = row_sets[r]\n for c in range(100):\n c_set = col_sets[c]\n # Check if union covers all 101 colors\n if len(r_set | c_set) == target_colors:\n colorful_count += 1\n\n # Verify the count against the requirement\n if colorful_count >= 9996:\n print(\"True\")\n else:\n print(f\"Error: Expected at least 9996 colorful cells, but found {colorful_count}.\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "ELMO-2014-P6", "category": "Extremal Problems", "id": "ELMO-2014-P6", "query": "A $2^{2014} + 1$ by $2^{2014} + 1$ grid has some black squares filled. The filled black squares form one or more snakes on the plane, each of whose heads splits at some points but never comes back together. In other words, for every positive integer $n$ greater than $2$, there do not exist pairwise distinct black squares $s_1, s_2, \\dots, s_n$ such that $s_i$ and $s_{i+1}$ share an edge for $i = 1, 2, \\dots, n$ (here $s_{n+1} = s_1$).What is the maximum possible number of filled black squares?", "ref_answer": "$\\frac{2(2^{2014}+1)(2^{2014}+2)}{3}-1$", "ref_solution": "Let $n = 2^m + 1$ be the dimension of the grid (for the given problem, $m = 2014$). Let $v$ be the number of filled black squares, and $e$ be the number of shared edges between black squares.\n\nSince the graph formed by the black squares contains no cycles, it is a forest, which implies $e \\le v - 1$.\nDouble-counting the edges of the black squares yields $3v + 1 \\le 4v - e$.\nThe total number of edges in the $n \\times n$ grid is $2n(n+1)$. Since $4v - e$ is the number of grid edges covered by at least one black square, we have $4v - e \\le 2n(n+1)$.\nThus, $3v + 1 \\le 2n(n+1)$.\n\nBecause $n = 2^m + 1$, for any $m \\ge 1$ we have $n \\not\\equiv 1 \\pmod 3$, which means $n(n+1)$ is a multiple of $3$.\nTherefore, $2n(n+1)$ is a multiple of $3$, and $3v + 1 \\le 2n(n+1)$ implies $3v \\le 2n(n+1) - 3$, yielding\n$$v \\le \\frac{2n(n+1)}{3} - 1.$$\nObserve that for $n \\not\\equiv 1 \\pmod 3$, this equality is achieved if and only if:\n(a) the graph formed by the black squares is a connected forest (i.e., a tree), and\n(b) all but two square edges belong to at least one black square.\n\nWe prove by induction on $m \\ge 1$ that equality can in fact be achieved.\nFor $m = 1$, take an “H-shape” on a $3 \\times 3$ grid (so if we set the center at $(0,0)$ in the coordinate plane, everything but $(0,\\pm 1)$ is black); call this configuration $G_1$. It is easy to verify that $G_1$ satisfies both conditions.\n\nTo go from $G_m$ to $G_{m+1}$, assume $G_m$ is defined on $[-2^{m-1}, 2^{m-1}]^2$. We define $G_{m+1}$ on $[-2^m, 2^m]^2$ as follows:\nfill in $(2x,2y)$ in $G_{m+1}$ if and only if $(x,y)$ is filled in $G_m$, and fill in $(x,y)$ with $x,y$ not both even if and only if $x + y$ is odd (so exactly one of $x,y$ is odd and the other is even).\n\nEach “newly-created” white square has both coordinates odd. Its four neighbors each have one even and one odd coordinate, so their coordinate sum is odd, meaning they are newly-created black squares. Thus, all four edges of any newly-created white square are covered by black squares.\nThe boundary of $G_{m+1}$ consists of squares with at least one coordinate equal to $\\pm 2^m$ (which is even), so no newly-created white square lies on the boundary.\nFurthermore, no two white squares can share an edge in $G_{m+1}$, because adjacent squares have different coordinate sum parities, and no square with an odd coordinate sum is white.\nTherefore, the only uncovered edges in $G_{m+1}$ are the boundary edges of the “old” white squares that lie on the boundary of the grid. By the inductive hypothesis, there are exactly two such uncovered edges (originating from the two white squares $(0, \\pm 1)$ in $G_1$). Thus $G_{m+1}$ satisfies (b).\n\nTo check that (a) holds, first we show that $(2x_1,2y_1)$ and $(2x_2,2y_2)$ are connected in $G_{m+1}$ if and only if $(x_1,y_1)$ and $(x_2,y_2)$ are black squares (and thus connected) in $G_m$ (the new black squares are essentially just “bridges”).\nIndeed, every path of black squares in $G_{m+1}$ must alternate between squares with odd and even coordinate sums, which corresponds to alternating between new and old black squares. Two old black squares $(2x_1,2y_1)$ and $(2x_2,2y_2)$ are adjacent to the same new black square $(x_1 + x_2, y_1 + y_2)$ in $G_{m+1}$ if and only if $(x_1,y_1)$ and $(x_2,y_2)$ are adjacent in $G_m$, whence the claim readily follows.\n\nThe rest is clear: the set of old black squares must remain connected in $G_{m+1}$, and all new black squares (including those on the boundary) border at least one old black square (otherwise, its two even-sum neighbors would both be white, meaning two white squares would be adjacent in $G_m$, which violates condition (b) for $G_m$). Thus, $G_{m+1}$ is fully connected.\n\nOn the other hand, $G_{m+1}$ cannot have any cycles. Since each new black square has at most two old black neighbors (its other two neighbors have both coordinates odd and are thus white), any cycle in $G_{m+1}$ would alternate between new and old black squares. Removing the new black squares from such a cycle would yield a corresponding cycle of old black squares in $G_m$, which contradicts the inductive hypothesis.\n\nThus, the maximum possible number of filled black squares is achieved. For the given problem where $n = 2^{2014} + 1$, the maximum number of filled black squares is $\\frac{2n(n+1)}{3} - 1$.", "grading_guidelines": "(Partial) 1. Interpreted the filled squares as a graph (vertices = black squares, edges = shared sides) and observed that the “no cycle” condition implies the graph is a forest, hence e ≤ v−1. 2. Double-counted square-sides to obtain an inequality of the form 3v+1 ≤ 4v−e (or an equivalent bound relating v and e via boundary/perimeter counting). 3. Combined the side-count with the grid-edge bound 4v−e ≤ 2n(n+1) to deduce 3v+1 ≤ 2n(n+1), hence v ≤ 2n(n+1)/3 − 1 after the divisibility observation for n=2^m+1. (Almost) 1. Derived the sharp upper bound v ≤ 2n(n+1)/3 − 1 and correctly identified the equality conditions (connected forest and exactly two uncovered grid-edges), but did not provide a full construction achieving equality. 2. Gave the recursive/inductive construction (from a 3×3 base pattern to size 2^m+1) intended to achieve equality, but left a localized gap in verifying either (i) no cycles are created, or (ii) only two edges remain uncovered (e.g. boundary case). 3. Provided a complete construction and matching-count argument for general n=2^m+1 but made a small arithmetic/parity slip that affects only the final −1 or a boundary case, while the main method is correct.", "instruction": "Provide a concrete construction for the 17x17 grid (the $N = 2^4+1$ case) that achieves the maximum possible number of filled black squares without forming any cycles.\n\nYour output must be a single, valid Python expression. When evaluated, this expression must return a 17x17 matrix (a list of lists) of strings, where \"1\" represents a filled black square and \"0\" represents an empty square. The orthogonally adjacent \"1\"s must form a forest (zero cycles), and the total count of \"1\"s must exactly equal the theoretical maximum for this 17x17 instance.\n\nDo not state the specific numerical maximum. Do not use hardcoded full-grid enumeration; use compact Python constructs like list comprehensions and conditional expressions. Do not include any imports, assignments, function definitions, markdown formatting, or explanatory text. Put ONLY the Python expression inside the `<construct>` block.", "ref_construction": "[[\"0\" if (i%2==1 and j%2==1) or (i%4==2 and j%4==2) or (i%8==4 and j%8==4) or (i%16==0 and j==8) else \"1\" for j in range(17)] for i in range(17)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty payload\")\n return\n\n try:\n grid = eval(payload, {\"__builtins__\": {}, \"range\": range}, {})\n except Exception as e:\n print(f\"Parse error: {e}\")\n return\n\n if not isinstance(grid, list) or len(grid) != 17:\n print(\"Grid must be a list of exactly 17 elements.\")\n return\n\n for row in grid:\n if not isinstance(row, list) or len(row) != 17:\n print(\"Each row must be a list of exactly 17 elements.\")\n return\n for cell in row:\n if not isinstance(cell, str) or cell not in [\"0\", \"1\"]:\n print(\"Each cell must be the string '0' or '1'.\")\n return\n\n count_ones = sum(cell == \"1\" for row in grid for cell in row)\n if count_ones != 203:\n print(f\"Total number of '1's must be exactly 203, but got {count_ones}.\")\n return\n\n visited = set()\n for i in range(17):\n for j in range(17):\n if grid[i][j] == \"1\" and (i, j) not in visited:\n stack = [(i, j, -1, -1)]\n while stack:\n curr_r, curr_c, parent_r, parent_c = stack.pop()\n if (curr_r, curr_c) in visited:\n print(\"Cycle detected among the '1's.\")\n return\n visited.add((curr_r, curr_c))\n \n for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n nr, nc = curr_r + dr, curr_c + dc\n if 0 <= nr < 17 and 0 <= nc < 17 and grid[nr][nc] == \"1\":\n if nr == parent_r and nc == parent_c:\n continue\n stack.append((nr, nc, curr_r, curr_c))\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "EMC-2017-P2", "category": "Extremal Problems", "id": "EMC-2017-P2", "query": "A football match lasts $90$ minutes. A team always has $11$ players on the field at the same time. The coach wants each player's playing time to be the same integer number of minutes.\n\n(1) If each player's playing time is less than $60$ minutes, what is the minimum number of players on the team?\n\n(2) Under the condition of the minimum number of players in (1), what is the minimum number of substitutions required?\n\nNote: Substitutions can only occur at integer minutes, the time for substitution is negligible, and substituted players can return to the field.", "ref_answer": "(1) $18$; (2) $17$", "ref_solution": "**Final Answers:**\n(1) $18$ players\n(2) $17$ substitutions\n\n**Part (1)**\nSuppose there are $n$ players on the team, and each player's playing time is exactly $k$ minutes. Both $n$ and $k$ must be positive integers. Since there are always $11$ players on the field during the $90$-minute match, the total playing time for all players combined is $11 \\times 90 = 990$ minutes. Therefore, we have the equation:\n$nk = 990$\n\nWe are given that each player's playing time is strictly less than $60$ minutes, so $k < 60$. Since $k$ must be an integer that divides $990$, the maximum possible value for $k$ is $55$. \nUsing $k \\le 55$, we find:\n$n = \\frac{990}{k} \\ge \\frac{990}{55} = 18$\nThus, the team must have a minimum of $18$ players.\n\n**Part (2)**\nAssume the team has the minimum of $18$ players, meaning each player plays exactly $55$ minutes. \n\nWe model the substitution process as a graph. Let each of the $18$ players be represented by a vertex. An edge is drawn between two vertices if one of the corresponding players directly substitutes the other. \n\nSuppose, for the sake of contradiction, that this graph is disconnected. Let the smallest connected component of the graph contain $l$ vertices. Since the graph is disconnected and has $18$ vertices in total, the smallest component can have at most half the vertices, meaning $l \\le \\frac{18}{2} = 9$. \n\nLet these $l$ vertices correspond to a specific group of players. Suppose that at any given time, there are $m$ players from this group on the field. Because substitutions within this component only happen among these $l$ players, the number of players $m$ from this group on the field must remain constant throughout the entire $90$-minute match. \n\nThe total playing time contributed by these $l$ players is $55l$ minutes. Since exactly $m$ players from this group are on the field at all times during the $90$-minute match, their total playing time can also be expressed as $90m$ minutes. Equating the two gives:\n$55l = 90m$\n$11l = 18m$\n\nSince $11$ and $18$ are coprime, $18$ must divide $l$. However, this implies $l \\ge 18$, which directly contradicts our earlier deduction that $l \\le 9$. \n\nTherefore, our assumption that the graph is disconnected must be false. The graph must be connected. A connected graph with $18$ vertices must have at least $18 - 1 = 17$ edges. Since each edge represents a substitution, there must be at least $17$ substitutions. \n\nThis theoretical minimum of $17$ substitutions can indeed be achieved in practice. It is possible to arrange the $11$ players on the field at each time such that exactly $17$ substitutions are made, with one substitution occurring every $5$ minutes.", "grading_guidelines": "(Partial) 1. Set up the counting equation total player-minutes = 11·90 = 990, hence if there are n players each playing k minutes then nk = 990 with n,k integers. 2. Used the constraint k < 60 to deduce a lower bound on n via a divisor bound for k (e.g. noting k ≤ 55 since 990 has no divisor in {56,57,58,59}), giving n ≥ 18. 3. For part (2), introduced a substitution graph (vertices = players, edge when one directly substitutes the other) and correctly argued that if the graph had a component of size l with m of its players always on the field, then 55l = 90m (or equivalent invariant), leading to a divisibility restriction on l. (Almost) 1. Correctly proved n = 18 is minimal in (1), and for (2) proved the substitution graph must be connected and hence at least 17 substitutions are necessary, but did not provide (or gave an incomplete) explicit schedule achieving 17 substitutions. 2. Gave a construction intending to realize 17 substitutions (e.g. substitutions every 5 minutes) and checked most player-times equal 55, but left a small number of players’ minutes (or a boundary time at start/end) unchecked/miscounted. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Provide an explicit 90-minute playing schedule for the minimum number of players $N$ found in part (1), such that each player's total playing time is the same integer and the total number of substitutions is minimized as in part (2).\n\nOutput requirements:\n- The construction must be a single Python expression. Evaluating this expression must directly return the required schedule list.\n- The value of the expression must be exactly one Python list of entries `[start, end, lineup]`.\n- `start` and `end` are the start and end times (in minutes) of a period where the lineup remains constant.\n- `lineup` is a sorted list of the 11 players on the field during that period.\n- Players must be numbered $1, 2, \\dots, N$.\n- The periods must be contiguous and cover the full 90 minutes.\n- All players must have the same integer total playing time, and this time must be less than 60 minutes.\n- A substitution is defined as a player entering the field who was not in the previous period's lineup. The total number of substitutions is the sum of these entrance counts across all transitions. This total must be minimized.\n- Do not use explanations, comments, assignments, imports, function definitions, or any non-expression content.\n- Put ONLY the Python expression inside the `<construct>` block.", "ref_construction": "[[5*i, 5*(i+1), sorted(((i+j) % 18) + 1 for j in range(11))] for i in range(18)]", "verify_code": "import sys\n\ndef verify():\n try:\n raw_input = sys.stdin.read().strip()\n if not raw_input:\n print(\"No input provided.\")\n return\n safe_globals = {\"__builtins__\": {}, \"range\": range, \"sorted\": sorted}\n data = eval(raw_input, safe_globals, {})\n except Exception as e:\n print(f\"Failed to evaluate construction: {e}\")\n return\n\n if not isinstance(data, list):\n print(\"Construction must evaluate to a list.\")\n return\n\n current_time = 0\n player_times = {}\n total_subs = 0\n previous_lineup = None\n\n for i, entry in enumerate(data):\n if not (isinstance(entry, list) and len(entry) == 3):\n print(f\"Entry {i} must be a list of [start, end, lineup].\")\n return\n\n start, end, lineup = entry\n\n if not (isinstance(start, int) and isinstance(end, int)):\n print(f\"Start and end times must be integers in entry {i}.\")\n return\n\n if start != current_time:\n print(f\"Gap or overlap in time at entry {i}: expected start {current_time}, got {start}.\")\n return\n\n if end <= start:\n print(f\"End time must be greater than start time in entry {i}.\")\n return\n\n if not isinstance(lineup, list) or len(lineup) != 11:\n print(f\"Lineup must be a list of 11 players in entry {i}.\")\n return\n\n if lineup != sorted(list(set(lineup))):\n print(f\"Lineup must be sorted and contain 11 distinct player IDs in entry {i}.\")\n return\n\n for p in lineup:\n if not isinstance(p, int) or p <= 0:\n print(f\"Player IDs must be positive integers in entry {i}.\")\n return\n player_times[p] = player_times.get(p, 0) + (end - start)\n\n if previous_lineup is not None:\n subs = len(set(lineup) - set(previous_lineup))\n total_subs += subs\n\n previous_lineup = lineup\n current_time = end\n\n if current_time != 90:\n print(f\"Schedule must cover exactly 90 minutes, but ends at {current_time}.\")\n return\n\n if not player_times:\n print(\"No players found in the schedule.\")\n return\n\n times = set(player_times.values())\n if len(times) != 1:\n print(f\"Not all players have the same playing time. Playing times: {player_times}\")\n return\n\n T = list(times)[0]\n if T >= 60:\n print(f\"Total playing time {T} must be less than 60 minutes.\")\n return\n\n N = len(player_times)\n if N != 18:\n print(f\"Number of players {N} is not the minimum required (18).\")\n return\n\n if set(player_times.keys()) != set(range(1, 19)):\n print(f\"Player IDs must be 1, 2, ..., 18. Found IDs: {sorted(player_times.keys())}\")\n return\n\n if total_subs != 17:\n print(f\"Total substitutions {total_subs} is not the minimum required (17).\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "EMC-2021-P1", "category": "Extremal Problems", "id": "EMC-2021-P1", "query": "A draws a regular 2021-gon in the plane. B labels each vertex with a real number such that the labels on any two adjacent vertices differ by at most 1. For any two non-adjacent vertices whose labels differ by at most 1, A draws a diagonal connecting them. Let $d$ denote the number of diagonals drawn by A. Find the minimum possible value of $d$.", "ref_answer": "The answer is $2018$.", "ref_solution": "The minimum possible value of $d$ is $2018$.\n\nThere exists a valid numbering of the vertices such that exactly $d = 2018$ diagonals are drawn.\n\nWe prove by induction that for a general $n$-gon ($n \\ge 3$), A must draw at least $n-3$ diagonals. \nWhen $n=3$, the number of diagonals drawn is at least $3-3=0$, which is obvious. \nAssume the statement holds for $n-1$, and consider the case $n$. Let the label on vertex $v$ be $a$, which is the smallest among all labels, and let the labels on the two vertices adjacent to $v$, namely $v_1$ and $v_2$, be $b$ and $c$, respectively. Since the labels on adjacent vertices differ by at most $1$, we have $0 \\le b-a \\le 1$ and $0 \\le c-a \\le 1$. This implies that $|b-c| \\le 1$, so $v_1$ and $v_2$ are connected by a diagonal. \n\nRemove vertex $v$ to obtain an $(n-1)$-gon; the segment $v_1v_2$ is an edge of this smaller polygon. By the induction hypothesis, this $(n-1)$-gon has at least $n-4$ diagonals. Adding the diagonal $v_1v_2$ shows that the original $n$-gon has at least $(n-4) + 1 = n-3$ diagonals. The induction is complete.\n\nFor $n=2021$, A must draw at least $2021-3 = 2018$ diagonals. Thus, the minimum possible value of $d$ is indeed $2018$.", "grading_guidelines": "(Partial) 1. Gave a labeling achieving $d=2018$ (or in general $d=n-3$), and correctly checked that adjacent vertices differ by at most 1 and that exactly those $2018$ non-adjacent pairs with label difference at most 1 occur. 2. Proved the key structural step: if $v$ has minimal label $a$ and its neighbors have labels $b,c$, then $0\\le b-a\\le1$ and $0\\le c-a\\le1$, hence $|b-c|\\le1$ and therefore $v_1v_2$ must be drawn. 3. Correctly set up the induction/reduction $n\\to n-1$ by removing a vertex of minimal label so that $v_1v_2$ becomes an edge of the smaller polygon, even if the diagonal-count conclusion is not fully justified. (Almost) 1. Proved the lower bound $d\\ge n-3$ (hence $d\\ge2018$) by induction using the minimal-label vertex and deletion, but did not provide (or incorrectly verified) a construction achieving $2018$. 2. Gave both the construction and the inductive lower bound idea, but left a small gap in the induction step (e.g. not justifying that diagonals in the $(n-1)$-gon are also diagonals of the original $n$-gon, or double-counting/omitting the added diagonal $v_1v_2$). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Provide an explicit labeling for the original regular 2021-gon: output exactly one Python expression which, when eval-ed, returns a list of 2021 real numbers (int/float), where the i-th entry is the label of vertex i (in cyclic order). The labels must satisfy that for every pair of adjacent vertices (including vertices 2021 and 1), the absolute difference of their labels is at most 1. Among all such labelings, your labeling must make the number of diagonals drawn by A (i.e., the number of unordered pairs of non-adjacent vertices whose labels differ by at most 1) as small as possible. Put the expression as the only content inside <construct>...</construct>.", "ref_construction": "[i if i <= 1010 else 2020.5 - i for i in range(2021)]", "verify_code": "import sys, math, ast\n\ndef fail(msg: str):\n print(msg)\n sys.exit(0)\n\ns = sys.stdin.read()\nif s is None:\n fail(\"Parse error: empty input\")\ns = s.strip()\nif not s:\n fail(\"Parse error: empty input\")\n\n# Parse as a Python expression (strict), then eval in restricted environment\ntry:\n tree = ast.parse(s, mode=\"eval\")\nexcept Exception as e:\n fail(f\"Parse error: {e}\")\n\ntry:\n codeobj = compile(tree, \"<stdin>\", \"eval\")\n val = eval(codeobj, {\"__builtins__\": {}, \"range\": range}, {})\nexcept Exception as e:\n fail(f\"Eval error: {e}\")\n\n# Check list length\nif not isinstance(val, list):\n fail(f\"Type error: expected a list, got {type(val).__name__}\")\nif len(val) != 2021:\n fail(f\"Length error: expected 2021 labels, got {len(val)}\")\n\n# Check each element is int/float (reject bool and non-finite)\na = val\nfor idx, x in enumerate(a):\n if isinstance(x, bool) or not isinstance(x, (int, float)):\n fail(f\"Element type error at index {idx}: expected int/float, got {type(x).__name__}\")\n if not math.isfinite(float(x)):\n fail(f\"Element value error at index {idx}: non-finite value {x!r}\")\n\n# Check adjacency constraints\nn = 2021\nfor i in range(n):\n j = (i + 1) % n\n diff = abs(float(a[i]) - float(a[j]))\n if diff > 1 + 1e-12:\n fail(f\"Adjacency constraint violated at indices ({i},{j}): values {a[i]!r}, {a[j]!r}, diff={diff}\")\n\n# Count diagonals\nd = 0\nfor i in range(n):\n ai = float(a[i])\n for j in range(i + 1, n):\n # adjacent if consecutive or (0, n-1)\n if j == i + 1 or (i == 0 and j == n - 1):\n continue\n if abs(ai - float(a[j])) <= 1 + 1e-12:\n d += 1\n\nif d != 2018:\n fail(f\"Diagonal count incorrect: computed d={d}, expected 2018\")\n\nprint(\"True\")"} | |
| {"split": "construction", "source": "EGMO-2025-P5", "category": "Operations and Strategies", "id": "EGMO-2025-P5", "query": "\"Given an integer $n>1$. An $n\\\\times n$ chessboard is called a direction diagram if each of its $n^2$ squares contains an arrow pointing to one of the four directions: up, down, left, or right. For an initial direction diagram, a turbo snail starts moving from a certain square on the chessboard. In each move, the snail advances one square in the direction of the arrow in its current square (it may move off the board). After each move, all arrows on the chessboard rotate $90^\\\\circ$ counterclockwise simultaneously. A square is called good if, starting from this square and moving according to the above rules, the snail passes through each square of the chessboard exactly once, never moves off the board, and finally returns to the initial square. For a given $n$, determine the maximum number of good squares over all possible initial direction diagrams.\n\"", "ref_answer": "It is $0$ when $n$ is odd, and $\\\\frac{n^2}{4}$ when $n$ is even.", "ref_solution": "The maximum number of good squares is $0$ when $n$ is odd, and $\\frac{n^2}{4}$ when $n$ is even.\n\nFor odd $n$, coloring the board black and white demonstrates that the snail moves between cells of alternating colors on each turn. Since the total number of cells is odd, a Hamiltonian cycle cannot exist, yielding exactly $0$ good cells.\n\nFor even $n$, choosing a Hamiltonian cycle and setting the initial arrow directions accordingly allows the starting cell to be good. Along this cycle, exactly one in every four consecutive cells is a good cell, because the arrow direction aligns with the required path only every four moves due to the simultaneous $90^\\circ$ rotations. This establishes a lower bound of $\\frac{n^2}{4}$ good cells.\n\nAt the top-left corner of the board, there are exactly four valid local configurations for the sequence of moves entering and exiting the corner cell. Because one cannot obtain another configuration by simultaneously rotating the three arrows involved in a given configuration, any fixed initial arrow diagram uniquely determines how a Hamiltonian cycle passes through the top-left corner. This uniquely dictates the subsequent route along the arrow directions, meaning there is only one valid Hamiltonian cycle. Since the number of moves from any good cell to the top-left corner must be congruent modulo $4$, the number of good cells is exactly $\\frac{n^2}{4}$.", "grading_guidelines": "(Partial) 1. For odd n, used a correct parity/colouring argument (e.g. checkerboard colouring) to show the snail alternates colours each move and hence a Hamiltonian cycle visiting all n^2 cells is impossible, concluding there are no good squares. 2. For even n, gave a valid construction from a Hamiltonian cycle: defined initial arrows so that starting from some chosen cell the snail follows the cycle while arrows rotate, producing at least one good square (or a positive proportion of them). 3. Established the key “mod 4” alignment fact: along any fixed cycle, a starting square is good only when the local required direction matches the current arrow orientation, which occurs with period 4, implying at most one in every four consecutive vertices on the cycle can be good. (Almost) 1. Correctly obtained the lower bound n^2/4 for even n via a Hamiltonian-cycle construction, but did not fully justify the matching upper bound (e.g. stated “at most one quarter are good” without a complete argument). 2. Proved the upper bound n^2/4 for even n using the mod-4 restriction, but left a small gap in showing that all good starting squares must lie in the same congruence class (e.g. did not rigorously justify why the path/cycle is uniquely forced from a corner or another anchoring configuration). 3. Gave a complete odd-n impossibility proof and the even-n framework, but made a localized mistake in the corner/local-configuration forcing step (or omitted checking a boundary/local case), while the rest of the solution is correct and would yield the stated maximum.", "instruction": "For the specific case $n=64$, determine a valid initial direction diagram that maximizes the number of \"good squares\". Provide an explicit construction for this diagram.\n\nConstruction requirements:\n- Output a single Python expression that evaluates to a $64 \\times 64$ list of lists of integers.\n- The integers must be in $\\{0, 1, 2, 3\\}$, representing the initial arrow directions: 0 for right, 1 for up, 2 for left, and 3 for down.\n- The output must be a pure Python expression (e.g., a list comprehension). Do not include any explanations, comments, markdown formatting, print statements, assignments, function definitions, imports, classes, asserts, or loops outside of comprehensions.\n- Prioritize using list comprehensions, conditional expressions, and integer constants to generate a compact, regular, and reproducible expression.\n- Put ONLY the Python expression inside the construction block.", "ref_construction": "[[(((0 if c < 63 else 3) if r == 0 else (1 if c == 0 else ((2 if c > 1 else (3 if r < 63 else 2)) if r % 2 == 1 else (0 if c < 63 else 3)))) - (c if r == 0 else (4096 - r if c == 0 else (r * 63 + 64 - c if r % 2 == 1 else r * 63 + c)))) % 4 for c in range(64)] for r in range(64)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n\n try:\n # Evaluate the payload to obtain the 64x64 grid\n # eval is used here to properly parse list comprehensions as required by the instruction\n grid = eval(payload)\n except Exception as e:\n print(f\"Failed to parse input: {e}\")\n return\n\n # Validate structural correctness\n if type(grid) is not list:\n print(\"Grid must be a list.\")\n return\n if len(grid) != 64:\n print(f\"Grid must have exactly 64 rows, got {len(grid)}.\")\n return\n \n flat_grid = [0] * 4096\n for i, row in enumerate(grid):\n if type(row) is not list:\n print(f\"Row {i} is not a list.\")\n return\n if len(row) != 64:\n print(f\"Row {i} must have exactly 64 elements, got {len(row)}.\")\n return\n for j, val in enumerate(row):\n if type(val) is not int or val not in {0, 1, 2, 3}:\n print(f\"Element at ({i}, {j}) is not an integer in {{0, 1, 2, 3}}.\")\n return\n flat_grid[(i << 6) | j] = val\n\n # Simulation setup\n visited = [0] * 4096\n attempt = 0\n good_squares_count = 0\n\n # Simulate snail movement from every possible starting square\n for r in range(64):\n for c in range(64):\n attempt += 1\n curr_r, curr_c = r, c\n success = True\n \n for t in range(4096):\n # Check out-of-bounds\n if curr_r < 0 or curr_r > 63 or curr_c < 0 or curr_c > 63:\n success = False\n break\n \n idx = (curr_r << 6) | curr_c\n \n # Check if already visited in the current attempt\n if visited[idx] == attempt:\n success = False\n break\n \n # Mark as visited\n visited[idx] = attempt\n \n # Calculate current direction with 90-degree counterclockwise rotation (adding 1 mod 4 per step)\n d = (flat_grid[idx] + t) & 3\n \n # Update coordinates\n if d == 0: # right\n curr_c += 1\n elif d == 1: # up\n curr_r -= 1\n elif d == 2: # left\n curr_c -= 1\n else: # down\n curr_r += 1\n \n # After 4096 steps, check if it successfully returned to the start\n if success and curr_r == r and curr_c == c:\n good_squares_count += 1\n\n # Verify that the maximum number of good squares is achieved\n if good_squares_count != 1024:\n print(f\"Expected 1024 good squares, but got {good_squares_count}.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "EGMO-2019-P2", "category": "Extremal Problems", "id": "EGMO-2019-P2-80", "query": "\"Given a positive integer $n$. Place several dominoes on a $2n\\\\times 2n$ grid such that every cell of the grid is adjacent to exactly one cell covered by a domino. Find the maximum number of dominoes that can be placed. Note: A domino is a $1\\\\times2$ or $2\\\\times1$ grid. Each domino must be placed on two cells of the grid, and different dominoes cannot overlap. Two distinct cells are called adjacent if they share a common edge.\n\"", "ref_answer": "$(n+1)n/2$", "ref_solution": "We will prove that the maximum number of dominoes that can be placed is $\\frac{n^2+n}{2}$. \n\nLet the cells of the $2n \\times 2n$ grid be denoted by coordinates $(x,y)$ for $1 \\le x, y \\le 2n$. We define the \"layer\" or \"depth\" of a cell as its distance from the boundary of the grid:\n$$ d(x,y) = \\min(x, 2n+1-x, y, 2n+1-y) $$\nNote that $1 \\le d(x,y) \\le n$. We color the grid with two colors, black and white, by defining the set of black cells $B$ as those belonging to odd layers:\n$$ B = \\{ (x,y) \\mid d(x,y) \\text{ is odd} \\} $$\n\n**Claim 1:** Every cell in the grid is adjacent to exactly two black cells.\n*Proof.* Let $(x,y)$ be a cell in layer $m$, so $d(x,y) = m$. Its neighbors can only belong to layers $m-1$, $m$, or $m+1$. \n- If $(x,y)$ is not a corner of its layer, it has exactly two neighbors in layer $m$, one neighbor in layer $m-1$, and one neighbor in layer $m+1$. Since $m-1$ and $m+1$ have the same parity, which is opposite to the parity of $m$, the cell $(x,y)$ has either 2 neighbors in an odd layer (if $m$ is odd) and 2 in an even layer, or 2 neighbors in an even layer (if $m$ is even) and 2 in an odd layer. In either case, it has exactly 2 neighbors in $B$.\n- If $(x,y)$ is a corner of layer $m$, it has exactly two neighbors in layer $m$, two neighbors in layer $m-1$, and zero neighbors in layer $m+1$. By the same parity argument, exactly two of its neighbors belong to $B$. (For $m=1$, the layer $m-1$ is empty, meaning the corner cell has only 2 neighbors in total, both of which are in layer $1 \\subseteq B$).\nThus, every cell in the grid has exactly two black neighbors.\n\n**Claim 2:** The total number of black cells is $2n^2 + 2n$.\n*Proof.* The layer $L_m = \\{(x,y) \\mid d(x,y) = m\\}$ forms a square border of size $(2n-2m+2) \\times (2n-2m+2)$. The number of cells in $L_m$ is $4(2n-2m+1) = 8n - 8m + 4$. Summing this over all odd $m \\in \\{1, 3, \\dots\\}$ up to $n$ yields exactly $2n^2 + 2n$ black cells.\n\n**Upper Bound:**\nLet $D$ be the set of cells covered by the dominoes. Suppose there are $k$ dominoes; since each domino covers exactly 2 cells, $|D| = 2k$. \nThe problem requires that every cell in the grid is adjacent to exactly one cell in $D$. Therefore, the total number of adjacencies (edges) between the set of all grid cells and $D$ must equal the total number of grid cells.\nBy restricting our focus to the black cells, the number of edges between $B$ and $D$ is exactly $|B| = 2n^2 + 2n$, because each black cell has exactly one neighbor in $D$. \nOn the other hand, by Claim 1, every cell in $D$ is adjacent to exactly two black cells. Thus, the number of edges between $B$ and $D$ can also be counted as $2|D| = 4k$. \nEquating the two counts gives $4k = 2n^2 + 2n$, which implies $k = \\frac{n^2+n}{2}$. This proves that any valid placement must consist of exactly $\\frac{n^2+n}{2}$ dominoes.\n\n**Construction of exactly $\\frac{n^2+n}{2}$ dominoes:**\nTo show that such a placement is always possible, we construct it layer by layer. For each odd layer $m \\in \\{1, 3, \\dots\\}$ with $m \\le n$, the subgrid bounded by $L_m$ has side length $S = 2n - 2m + 2$. We place exactly $S - 1$ dominoes on $L_m$ using local coordinates $(i,j)$ for $1 \\le i, j \\le S$ (which correspond to global coordinates $(i+m-1, j+m-1)$).\n\n- **If $S \\equiv 2 \\pmod 4$:**\n - **Top edge:** Horizontal dominoes covering $(1, j)$ and $(1, j+1)$ for $j \\in \\{1, 5, 9, \\dots, S-1\\}$.\n - **Bottom edge:** Horizontal dominoes covering $(S, j)$ and $(S, j+1)$ for $j \\in \\{3, 7, 11, \\dots, S-3\\}$.\n - **Left edge:** Vertical dominoes covering $(i, 1)$ and $(i+1, 1)$ for $i \\in \\{4, 8, 12, \\dots, S-2\\}$.\n - **Right edge:** Vertical dominoes covering $(i, S)$ and $(i+1, S)$ for $i \\in \\{4, 8, 12, \\dots, S-2\\}$.\n\n- **If $S \\equiv 0 \\pmod 4$:**\n - **Top edge:** Horizontal dominoes covering $(1, j)$ and $(1, j+1)$ for $j \\in \\{2, 6, 10, \\dots, S-2\\}$.\n - **Bottom edge:** Horizontal dominoes covering $(S, j)$ and $(S, j+1)$ for $j \\in \\{4, 8, 12, \\dots, S-4\\}$.\n - **Left edge:** Vertical dominoes covering $(i, 1)$ and $(i+1, 1)$ for $i \\in \\{3, 7, 11, \\dots, S-1\\}$.\n - **Right edge:** Vertical dominoes covering $(i, S)$ and $(i+1, S)$ for $i \\in \\{3, 7, 11, \\dots, S-1\\}$.\n\nThis staggered boundary placement ensures that every cell in the grid is adjacent to exactly one covered cell. Summing the dominoes placed across all odd layers gives $\\sum_{m \\text{ odd}} (S - 1) = \\frac{n^2+n}{2}$.\n\nThus, the maximum number of dominoes that can be placed is $\\frac{n^2+n}{2}$.", "grading_guidelines": "(Partial) 1. Introduced the layer depth d(x,y)=min(x,2n+1−x,y,2n+1−y) and the colouring by parity of d, and correctly proved the key local fact that every cell has exactly two neighbours in odd layers (equivalently: exactly two black neighbours). 2. Counted the number of black cells by summing the sizes of the odd layers (or an equivalent correct counting), obtaining |B|=2n^2+2n (or an equivalent explicit formula). 3. Set up a correct double-counting of edges between black cells and covered cells D to derive a linear relation 4k=|B| (or equivalent), thus giving the upper bound k≤(n^2+n)/2, even if the details are incomplete. (Almost) 1. Gave the correct double-counting argument and obtained k=(n^2+n)/2 as a necessary value, but did not provide a complete existence construction (or only sketched it without verifying the adjacency condition everywhere). 2. Provided a near-complete layer-by-layer construction achieving (n^2+n)/2 dominoes, but left a small gap (e.g. one boundary/parity case S≡0 or 2 (mod 4) not checked, or a corner/last-layer adjacency not fully verified). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For the specific case $n=80$, provide an explicit construction for the maximum number of dominoes.\n\nConstruction requirements:\n- Output a single Python expression (using list comprehensions) that evaluates to a flat list of tuples.\n- Each tuple must be a 1-indexed coordinate `(r, c)` representing a cell on the $160 \\times 160$ grid.\n- Adjacent tuples at indices $2i$ and $2i+1$ represent a single domino covering those two cells.\n- The configuration must maximize the number of dominoes placed, while satisfying the condition that every cell in the $160 \\times 160$ grid is adjacent to exactly one cell covered by a domino.\n\nOutput formatting requirements:\n- The output must be a single, valid Python expression.\n- Do NOT wrap the output in markdown code blocks (e.g., no ```python ... ```).\n- Do NOT include any explanations, comments, print statements, or assignments.\n- Put ONLY the Python expression inside the construction block.", "ref_construction": "[cell for k in range(1, 41) for j in range(1, 42 - k) for cell in ((2*k-1, 2*k + 4*j - 4), (2*k-1, 2*k + 4*j - 3))] + [cell for k in range(40, 1, -1) for j in range(1, 42 - k) for cell in ((164 - 2*k, 2*k + 4*j - 4), (164 - 2*k, 2*k + 4*j - 3))] + [cell for k in range(1, 41) for col in (2*k - 1, 162 - 2*k) for j in range(1, 42 - k) for cell in ((2*k + 4*j - 3, col), (2*k + 4*j - 2, col))]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n\n try:\n # Evaluate the raw construction payload to support list comprehensions\n dominoes_cells = eval(payload)\n except Exception as e:\n print(f\"Failed to parse input: {e}\")\n return\n\n if not isinstance(dominoes_cells, list):\n print(\"Output must be a list.\")\n return\n \n if len(dominoes_cells) != 6480:\n print(f\"Expected exactly 6480 cells (3240 dominoes), got {len(dominoes_cells)}.\")\n return\n\n for cell in dominoes_cells:\n if not (isinstance(cell, tuple) and len(cell) == 2):\n print(f\"Invalid cell format: {cell}. Expected a 2-tuple.\")\n return\n r, c = cell\n if type(r) is not int or type(c) is not int:\n print(f\"Coordinates must be integers: {cell}.\")\n return\n if not (1 <= r <= 160 and 1 <= c <= 160):\n print(f\"Coordinates out of bounds: {cell}. Expected range [1, 160].\")\n return\n\n for i in range(0, 6480, 2):\n c1 = dominoes_cells[i]\n c2 = dominoes_cells[i+1]\n dist = abs(c1[0] - c2[0]) + abs(c1[1] - c2[1])\n if dist != 1:\n print(f\"Cells at indices {i} and {i+1} do not form a valid domino: {c1}, {c2}. Manhattan distance is {dist}, expected 1.\")\n return\n\n covered_cells = set(dominoes_cells)\n if len(covered_cells) != 6480:\n print(\"Overlapping dominoes detected. Covered cells are not completely distinct.\")\n return\n\n # Check neighbor count for every cell in the 160x160 grid\n for r in range(1, 161):\n for c in range(1, 161):\n neighbors = [\n (r-1, c),\n (r+1, c),\n (r, c-1),\n (r, c+1)\n ]\n count = sum(1 for nr, nc in neighbors if (nr, nc) in covered_cells)\n if count != 1:\n print(f\"Cell ({r}, {c}) is adjacent to {count} covered cells, expected exactly 1.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "EGMO-2016-P5", "category": "Extremal Problems", "id": "EGMO-2016-P5", "query": "\"Let integers $k,n$ satisfy $k\\\\geq2$, $k\\\\leq n\\\\leq 2k-1$. Place some $1\\\\times k$ or $k\\\\times 1$ rectangular cards on an $n\\\\times n$ grid such that each card covers exactly $k$ cells, no two cards overlap, and no additional card can be placed. Determine the minimum possible number of cards placed among all such placements.\n\"", "ref_answer": "When $n=k$ it is $n$, and when $k+1\\le n\\le 2k-1$ it is $\\min\\{n,2n-2k+2\\}$", "ref_solution": "The minimum possible number of cards is $n$ when $n=k$, and $\\min\\{n, 2n-2k+2\\}$ when $k+1 \\le n \\le 2k-1$.\n\n**Constructions:**\nWhen $n=k$, a total of $n$ pieces can be placed by filling the grid with $n$ horizontal pieces (one in each row) or $n$ vertical pieces (one in each column). Because a piece of length $k$ in a $k\\times k$ grid spans an entire row or column, placing even one horizontal piece prevents any vertical piece from being placed, and vice versa. Thus, all pieces must be of the same orientation, and a maximal placement requires exactly $n$ pieces.\n\nWhen $k+1 \\le n \\le 2k-2$, $2n-2k+2$ pieces can be placed as follows: \nIn the upper-left $(k+1)\\times(k+1)$ square, place $4$ pieces arranged in a pinwheel fashion: a $1\\times k$ piece in row $1$, columns $1$ to $k$; a $k\\times 1$ piece in column $k+1$, rows $1$ to $k$; a $1\\times k$ piece in row $k+1$, columns $2$ to $k+1$; and a $k\\times 1$ piece in column $1$, rows $2$ to $k+1$. This leaves a central $(k-1)\\times(k-1)$ empty square. For the remaining grid, the next $n-k-1$ rows (rows $k+2$ to $n$) each contain one $1\\times k$ horizontal piece in columns $1$ to $k$, and the next $n-k-1$ columns (columns $k+2$ to $n$) each contain one $k\\times 1$ vertical piece in rows $1$ to $k$. It is easy to verify that no additional piece can be inserted, as the remaining empty spaces are too small to accommodate a $k$-length piece. This uses exactly $4 + 2(n-k-1) = 2n-2k+2$ pieces.\n\nWhen $n=2k-1$, $n$ pieces can be placed as follows: all pieces are placed vertically, alternating between the topmost and bottommost positions of each column. Specifically, for each column $j$ from $1$ to $n$, place a $k\\times 1$ piece in rows $1$ to $k$ if $j$ is odd, and in rows $k$ to $2k-1$ if $j$ is even. It is easy to verify that no additional piece can be inserted at this stage, as each column has only $k-1$ empty cells, and any row has at most $1$ consecutive empty cell (row $k$ has none), meaning no $1\\times k$ or $k\\times 1$ piece can fit.\n\n**Proof of the Lower Bound:**\nWhen $k+1 \\le n \\le 2k-1$, we prove that any placement satisfying the requirements contains at least $\\min\\{n, 2n-2k+2\\}$ pieces. Let $r$ be the number of rows that do not contain any horizontal piece, and $c$ be the number of columns that do not contain any vertical piece. \n\nIf $r=0$ or $c=0$, then at least $n$ pieces are placed. (For instance, if $r=0$, every row contains at least one horizontal piece. Since a horizontal piece is contained entirely in one row, there must be at least $n$ horizontal pieces.)\n\nIf both $r$ and $c$ are non-zero, we prove that at least $2n-2k+2$ pieces are placed. Consider a horizontal piece $T$. Since $n < 2k$, the top or bottom boundary of the board is at most $k-1$ rows away from the row containing $T$. Assume without loss of generality that the top boundary is closer. Let $y$ be the row containing $T$; then $y-1 \\le k-1$. The rows strictly between $T$ and the top boundary (rows $1$ to $y-1$) intersect the $k$ columns occupied by $T$, forming a rectangular region of size $(y-1) \\times k$. \n\nThis region cannot accommodate a vertical piece, because any vertical piece intersecting this region must not overlap with $T$, and thus would be restricted to rows $1$ to $y-1$. However, $y-1 < k$, so a $k \\times 1$ vertical piece cannot fit. Therefore, no vertical piece intersects this region. Since the placement is maximal, no additional horizontal piece can be placed. Thus, every row in this region must already share at least one cell with a horizontal piece (otherwise, all $k$ cells in that row within the region would be empty, allowing a new horizontal piece to be placed). \n\nSince a horizontal piece is entirely contained in a single row, this means every row from $1$ to $y-1$ must contain a horizontal piece. This argument shows that for any row containing a horizontal piece, all rows between it and the closest boundary (top or bottom) must also contain a horizontal piece. Consequently, the set of rows containing a horizontal piece forms a union of a prefix of rows and/or a suffix of rows. Therefore, the $r$ rows lacking a horizontal piece must be strictly consecutive. \n\nSimilarly, all $c$ columns lacking a vertical piece are consecutive. The $r$ rows and $c$ columns thus intersect to form an $r \\times c$ rectangular region. Because no horizontal piece is in these $r$ rows and no vertical piece is in these $c$ columns, this region contains no pieces at all. Since no new piece can be placed in this empty region, we must have $r < k$ and $c < k$. \n\nConsequently, there are $n-r \\ge n-k+1$ rows that each contain at least one horizontal piece, implying there are at least $n-k+1$ horizontal pieces. Similarly, there are $n-c \\ge n-k+1$ columns that each contain at least one vertical piece, implying there are at least $n-k+1$ vertical pieces. Hence, at least $(n-k+1) + (n-k+1) = 2n-2k+2$ pieces are placed in total. This completes the proof.", "grading_guidelines": "(Partial) 1. Gave a correct construction achieving the upper bound in at least one nontrivial case (e.g. the pinwheel-based construction with exactly $2n-2k+2$ cards for $k+1\\le n\\le 2k-2$, or the alternating-columns construction with $n$ cards for $n=2k-1$), and justified maximality of that construction. 2. Proved the structural claim that if both orientations occur in a maximal placement then the set of rows containing a horizontal card is a union of a top prefix and a bottom suffix (equivalently, the rows with no horizontal card form one consecutive block), and analogously for columns/vertical cards. 3. Established a valid lower bound of the right order, e.g. showed that if $r$ rows have no horizontal card and $c$ columns have no vertical card, then the $r\\times c$ intersection must be empty and hence $r<k$ and $c<k$, leading to at least $(n-k+1)+(n-k+1)=2n-2k+2$ cards (even if some details/cases are incomplete). (Almost) 1. Correctly derived the lower bound $\\ge \\min\\{n,2n-2k+2\\}$ for all $k\\le n\\le 2k-1$ via the $r,c$ argument (including the consecutive-block property and the conclusion $r,c<k$), but did not fully present/verify a matching construction in one of the subranges. 2. Provided matching constructions for all required ranges and proved the lower bound, but left a small gap in the maximality check (e.g. did not fully justify why no additional horizontal/vertical card fits in the remaining empty region, or omitted a boundary subcase such as $n=k$ or $n=2k-1$). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For the specific case $n=19$ and $k=10$, provide an explicit construction of a valid card placement that achieves the minimum possible number of cards.\n\nConstruction requirements:\n- Output a single Python list of lists, where each inner list represents a single card.\n- Each card should be represented by its two endpoints as a list of two tuples: `[(r1, c1), (r2, c2)]`, where `r` is the row index and `c` is the column index, with `r1 <= r2` and `c1 <= c2`.\n- Use 0-based indexing for coordinates on the $19 \\times 19$ grid, so `r` and `c` are integers from 0 to 18.\n- For example, a card covering from row 0 to 9 in column 0 is `[(0, 0), (9, 0)]`.\n- The placement must be unextendable (no additional $1 \\times 10$ or $10 \\times 1$ card can be placed anywhere on the grid without overlapping existing cards).\n- The number of cards must be exactly the minimum possible for this unextendable condition.\n- Put ONLY the Python expression (e.g., a literal list or a list comprehension) inside the construction block.", "ref_construction": "[[(0, c), (9, c)] if c % 2 == 0 else [(9, c), (18, c)] for c in range(19)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n\n # Parse the construction payload safely\n try:\n # We supply 'range' in locals to support list comprehensions as seen in the ref_construction\n cards = eval(payload, {\"__builtins__\": {}}, {\"range\": range})\n except Exception as e:\n print(f\"Failed to parse construction: {e}\")\n return\n\n # 1. Verify the parsed object is a list\n if type(cards) is not list:\n print(\"Construction must be a list of lists.\")\n return\n\n # 2. Check total number of cards\n if len(cards) != 19:\n print(f\"Expected exactly 19 cards, but got {len(cards)}.\")\n return\n\n # Initialize a 19x19 boolean grid to track occupied cells\n grid = [[False] * 19 for _ in range(19)]\n\n for i, card in enumerate(cards):\n # 3. Verify each card is a list containing exactly two endpoints\n if type(card) is not list:\n print(f\"Card at index {i} is not a list.\")\n return\n if len(card) != 2:\n print(f\"Card at index {i} does not contain exactly two endpoints.\")\n return\n \n ep1, ep2 = card\n \n # 4. Verify endpoints are tuples of two integers\n if type(ep1) is not tuple or len(ep1) != 2 or type(ep2) is not tuple or len(ep2) != 2:\n print(f\"Endpoints of card {i} must be tuples of length 2.\")\n return\n \n r1, c1 = ep1\n r2, c2 = ep2\n \n if not (type(r1) is int and type(c1) is int and type(r2) is int and type(c2) is int):\n print(f\"Coordinates of card {i} must be integers.\")\n return\n \n # 5. Verify coordinates are within bounds and properly ordered\n if not (0 <= r1 <= r2 <= 18 and 0 <= c1 <= c2 <= 18):\n print(f\"Coordinates of card {i} are out of bounds or improperly ordered.\")\n return\n \n # 6. Verify dimensions to ensure it covers exactly 10 cells\n if not ((r1 == r2 and c2 - c1 == 9) or (c1 == c2 and r2 - r1 == 9)):\n print(f\"Card {i} does not cover exactly 10 cells.\")\n return\n \n # 7. Mark cells on the grid and check for overlaps\n for r in range(r1, r2 + 1):\n for c in range(c1, c2 + 1):\n if grid[r][c]:\n print(f\"Card {i} overlaps with an existing card at ({r}, {c}).\")\n return\n grid[r][c] = True\n\n # 8. Verify the placement is strictly unextendable\n # Scan all 19 rows\n for r in range(19):\n consecutive_false = 0\n for c in range(19):\n if not grid[r][c]:\n consecutive_false += 1\n if consecutive_false >= 10:\n print(f\"Placement is extendable: a 1x10 card can be placed in row {r}.\")\n return\n else:\n consecutive_false = 0\n\n # Scan all 19 columns\n for c in range(19):\n consecutive_false = 0\n for r in range(19):\n if not grid[r][c]:\n consecutive_false += 1\n if consecutive_false >= 10:\n print(f\"Placement is extendable: a 10x1 card can be placed in column {c}.\")\n return\n else:\n consecutive_false = 0\n\n # All checks passed\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "APMO-2024-P2", "category": "Counting", "id": "APMO-2024-P2", "query": "In a $100\\\\times100$ grid, let $(a,b)$ denote the cell in the $a$-th row and $b$-th column. For an integer $51\\\\leq k\\\\leq 99$, a $k$-knight moves one step horizontally or vertically and $k$ steps in the other direction. The $k$-knight starts at cell $(1,1)$. A moving sequence is a sequence of cells $(x_0,y_0)=(1,1)$, $(x_1,y_1)$, $\\\\cdots$, $(x_n,y_n)$ such that for $i=1$, $2$, $\\\\cdots$, $n$, $1\\\\leq x_i,y_i\\\\leq 100$, and the $k$-knight can move from $(x_{i-1},y_{i-1})$ to $(x_i,y_i)$. The cells $(x_i,y_i)$ are called reachable. For each $k$, find the number of reachable cells $L(k)$.", "ref_answer": "When $k$ is even, $L(k)=4k(100-k)$; when $k$ is odd, $L(k)=2k(100-k)$.", "ref_solution": "We prove that for every integer $51 \\le k \\le 99$,\n\\[\nL(k)=\n\\begin{cases}\n4k(100-k), & k \\text{ even},\\\\\n2k(100-k), & k \\text{ odd}.\n\\end{cases}\n\\]\n\nFirst determine which cells can possibly be reached by one move from another cell. A cell $(x,y)$ is directly reachable from some other cell if and only if at least one of\n\\[\nx-k\\ge 1,\\qquad x+k\\le 100,\\qquad y-k\\ge 1,\\qquad y+k\\le 100\n\\]\nholds. Equivalently,\n\\[\nx\\ge k+1 \\quad\\text{or}\\quad x\\le 100-k \\quad\\text{or}\\quad y\\ge k+1 \\quad\\text{or}\\quad y\\le 100-k. \\tag{1}\n\\]\nIndeed, a $k$-knight move changes one coordinate by $k$ and the other coordinate by $1$; hence, in order to land at $(x,y)$, one of the four cells obtained by changing either coordinate by $k$ must still lie on the board.\n\nTherefore every cell satisfying\n\\[\n101-k\\le x\\le k,\n\\qquad\n101-k\\le y\\le k\n\\]\nis unreachable. Let\n\\[\nS=\\{(x,y):101-k\\le x\\le k,\\ 101-k\\le y\\le k\\}.\n\\]\nThis is the central square of unreachable cells. Its side length is\n\\[\nk-(101-k)+1=2k-100,\n\\]\nso the number of cells outside $S$ is\n\\[\n100^2-(2k-100)^2=4k(100-k). \\tag{2}\n\\]\nThus $L(k)\\le 4k(100-k)$.\n\nWe now show that all cells outside $S$ are reachable when $k$ is even, and exactly the cells outside $S$ with the same chessboard color as $(1,1)$ are reachable when $k$ is odd.\n\nColor the board like a chessboard, according to the parity of $x+y$. A $k$-knight move changes $x+y$ by one of $\\pm k\\pm1$. Hence if $k$ is odd, every move preserves the color, while if $k$ is even, every move changes the color.\n\nThe key observation is that, outside $S$, one can move between same-colored neighboring cells by two $k$-knight moves. More precisely, suppose $(x,y)$ and one of $(x,y\\pm2)$, $(x\\pm2,y)$ both lie on the board and both satisfy condition (1). If the usable coordinate is on the lower side, for example $x\\le 100-k$, then\n\\[\n(x,y)\\to (x+k,y\\pm1)\n \\to (x,y\\pm2)\n\\]\nis a legal two-move path whenever the displayed cells are on the board. If $x\\ge k+1$, we instead use\n\\[\n(x,y)\\to (x-k,y\\pm1)\n \\to (x,y\\pm2).\n\\]\nSimilarly, if $y\\le 100-k$, then\n\\[\n(x,y)\\to (x\\pm1,y+k)\n \\to (x\\pm2,y),\n\\]\nand if $y\\ge k+1$, then\n\\[\n(x,y)\\to (x\\pm1,y-k)\n \\to (x\\pm2,y).\n\\]\nThus any allowed step by $(\\pm2,0)$ or $(0,\\pm2)$ between cells outside $S$ can be realized by two legal $k$-knight moves.\n\nSince $S$ is a central square and $k\\ge 51$, the cells outside $S$ form a frame around it. Within each chessboard color, this frame is connected by steps of the form $(\\pm2,0)$ and $(0,\\pm2)$. Starting from $(1,1)$, which lies outside $S$, the previous paragraph shows that every cell outside $S$ with the same color as $(1,1)$ is reachable.\n\nIf $k$ is odd, the color is preserved by every move, so no cell of the opposite color can be reached. The board has even side length, and the square $S$ also has even side length $2k-100$, so the cells outside $S$ are split equally between the two colors. Therefore\n\\[\nL(k)=\\frac12\\bigl(100^2-(2k-100)^2\\bigr)=2k(100-k).\n\\]\n\nIf $k$ is even, every move changes color. Let $(x,y)$ be any cell outside $S$ whose color is opposite to that of $(1,1)$. Since $(x,y)$ satisfies condition (1), it has a legal predecessor or successor by a $k$-knight move inside the board; that adjacent cell has the same color as $(1,1)$ and is also outside $S$. As shown above, that adjacent cell is reachable, so one more move reaches $(x,y)$. Hence every cell outside $S$ is reachable, and by (2)\n\\[\nL(k)=100^2-(2k-100)^2=4k(100-k).\n\\]\n\nThis proves the desired formula.", "grading_guidelines": "(Partial) 1. Identified the central square S of cells with 101−k≤x≤k and 101−k≤y≤k as unreachable (e.g. by proving a necessary condition for landing at (x,y): x≥k+1 or x≤100−k or y≥k+1 or y≤100−k). 2. Correctly counted the number of cells outside S as 100^2−(2k−100)^2=4k(100−k), obtaining the upper bound L(k)≤4k(100−k). 3. Made a correct parity/color observation: a k-knight move preserves chessboard color iff k is odd, and flips color iff k is even. (Almost) 1. Established reachability of all cells outside S of the same color as (1,1) by exhibiting the key two-move simulation of (±2,0) and (0,±2) steps between admissible cells, but did not fully justify that the outside-of-S frame is connected (within a color) by these steps. 2. Correctly derived the odd-k case L(k)=2k(100−k) from color preservation and the count of outside-of-S cells, but the argument that the outside-of-S cells split equally between the two colors is missing or flawed. 3. Correctly derived the even-k case L(k)=4k(100−k) from reachability of one color plus one extra move to the opposite color, but left a localized gap in proving every opposite-colored cell outside S has a valid adjacent (by a k-knight move) same-colored cell still outside S. 4. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For the specific case $k=68$, provide an explicit construction of a path from the starting cell $(1,1)$ to every reachable cell.\n\nConstruction requirements:\n- The output must be a SINGLE valid Python expression that evaluates to a dictionary.\n- The dictionary should map each reachable cell `(x, y)` to its corresponding path.\n- A path must be represented as a list of tuples `[(1,1), (x_1, y_1), ..., (x, y)]`, where each consecutive pair of cells represents a valid move for a 68-knight on the $100 \\times 100$ grid.\n- Do not use any assignment statements, `import` statements, `for` loops (outside of comprehensions), or any non-expression syntax.\n- You may use lambda functions, comprehensions, and dictionary unpacking to generate the paths algorithmically.\n- Put ONLY the Python expression inside the `<construct>` block.", "ref_construction": "(lambda adj: (lambda bfs: bfs(bfs, {}, {(1, 1): [(1, 1)]}))(\n lambda f, v, frontier: {**v, **frontier} if not frontier else f(\n f,\n {**v, **frontier},\n {n: frontier[u] + [n] for u in frontier for n in adj(u) if n not in v and n not in frontier}\n )\n))(lambda u: [(u[0]+dx, u[1]+dy) for dx, dy in [(1,68), (1,-68), (-1,68), (-1,-68), (68,1), (68,-1), (-68,1), (-68,-1)] if 1<=u[0]+dx<=100 and 1<=u[1]+dy<=100])", "verify_code": "import sys\n\ndef verify():\n # Increase recursion limit to support deep recursive lambda functions (e.g., BFS implementations)\n sys.setrecursionlimit(20000)\n \n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty payload.\")\n return\n\n try:\n # The instruction specifies the output must be a SINGLE valid Python expression.\n # eval() enforces this and supports algorithmic generation (lambdas, comprehensions).\n paths_dict = eval(payload)\n except Exception as e:\n print(f\"Failed to evaluate payload: {e}\")\n return\n\n if not isinstance(paths_dict, dict):\n print(f\"Payload evaluated to {type(paths_dict).__name__}, expected dict.\")\n return\n\n # Check for the exact number of reachable cells for k=68 on a 100x100 grid\n # Formula: L(k) = 4k(100-k) -> 4 * 68 * 32 = 8704\n if len(paths_dict) != 8704:\n print(f\"Dictionary contains {len(paths_dict)} keys, expected exactly 8704.\")\n return\n\n for target, path in paths_dict.items():\n # Validate key format\n if not isinstance(target, tuple) or len(target) != 2:\n print(f\"Key {target} is not a 2-tuple.\")\n return\n \n tx, ty = target\n if type(tx) is not int or type(ty) is not int:\n print(f\"Key {target} contains non-integer coordinates.\")\n return\n \n # Validate path format\n if not isinstance(path, list):\n print(f\"Path for {target} is not a list.\")\n return\n \n if not path:\n print(f\"Path for {target} is empty.\")\n return\n\n if path[0] != (1, 1):\n print(f\"Path for {target} does not start with (1, 1).\")\n return\n \n if path[-1] != target:\n print(f\"Path for {target} does not end with its key {target}.\")\n return\n\n # Validate all cells in the path\n for cell in path:\n if not isinstance(cell, tuple) or len(cell) != 2:\n print(f\"Cell {cell} in path for {target} is not a 2-tuple.\")\n return\n x, y = cell\n if type(x) is not int or type(y) is not int:\n print(f\"Coordinates of cell {cell} in path for {target} are not integers.\")\n return\n if not (1 <= x <= 100 and 1 <= y <= 100):\n print(f\"Cell {cell} in path for {target} is out of 100x100 grid bounds.\")\n return\n\n # Validate consecutive moves in the path\n for i in range(len(path) - 1):\n x1, y1 = path[i]\n x2, y2 = path[i+1]\n dx = abs(x2 - x1)\n dy = abs(y2 - y1)\n \n # A valid 68-knight move must have absolute coordinate differences of exactly {1, 68}\n if {dx, dy} != {1, 68}:\n print(f\"Invalid 68-knight move from {path[i]} to {path[i+1]} in path for {target}.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "APMO-2012-P2", "category": "Operations and Strategies", "id": "APMO-2012-P2", "query": "In a $2012\\\\times2012$ grid, each cell is filled with a real number from the interval $[0,1]$. The grid is divided into two smaller rectangular grids by drawing a straight line parallel to the edges. If for every possible division, at least one of the smaller grids has the sum of all its numbers not greater than $1$, find the maximum possible sum of all numbers in the entire grid.", "ref_answer": "5", "ref_solution": "We first construct a grid where the sum of all numbers is $5$. Let the top-left $3\\times3$ cells of the grid be filled such that the cells $(1,2), (2,1), (2,2), (2,3),$ and $(3,2)$ contain $1$, and the remaining four cells in this $3\\times 3$ block contain $0$. All other cells in the $2012\\times 2012$ grid are filled with $0$. It is easy to verify that the requirement is satisfied: for any horizontal or vertical division, the sum of the numbers in one of the resulting parts is at most $1$ (in fact, exactly $1$ or $0$). The sum of all numbers in this grid is $5$.\n\nNext, we prove that for every grid satisfying the conditions, the sum of all numbers does not exceed $5$. Assume the total sum of the grid is greater than $1$ (otherwise the bound of $5$ trivially holds). Consider the division after the first row. By the problem condition, either the first row has sum $\\le 1$, or the remaining $2011$ rows have sum $\\le 1$. In the latter case, since all entries are non-negative, the last row must also have sum $\\le 1$. Thus, the sum of the numbers in the first row or the last row does not exceed $1$; by symmetry, we may assume it is the former.\n\nSince the sum of the first row is at most $1$ and the total sum is greater than $1$, there exists a largest positive integer $i$ such that the sum of the numbers in the first $i-1$ rows does not exceed $1$. By the maximality of $i$, the sum of the numbers in the first $i$ rows is greater than $1$. Therefore, by the problem's condition applied to the cut after the $i$-th row, the sum of the numbers in the last $2012-i$ rows does not exceed $1$.\n\nSimilarly, by considering vertical divisions, there exists a positive integer $j$ such that the sum of the numbers in the first $j-1$ columns does not exceed $1$, and the sum of the numbers in the last $2012-j$ columns does not exceed $1$.\n\nNotice that every cell in the grid is covered by at least one of the following five regions:\n- The first $i-1$ rows\n- The last $2012-i$ rows\n- The first $j-1$ columns\n- The last $2012-j$ columns\n- The single intersecting cell at row $i$, column $j$\n\nTo see this, observe that any cell not in the first $i-1$ rows and not in the last $2012-i$ rows must lie in row $i$. If it is in row $i$, and it is not in the first $j-1$ columns and not in the last $2012-j$ columns, it must be exactly the cell at row $i$, column $j$.\n\nSince all numbers in the grid are non-negative, the total sum of all numbers is bounded by the sum of the totals of these five regions. The sum of each of the first four regions does not exceed $1$, and the value in the cell at row $i$, column $j$ is in $[0,1]$, so it also does not exceed $1$. Therefore, the total sum of all numbers in the grid does not exceed $1+1+1+1+1=5$.", "grading_guidelines": "(Partial) 1. Gave a concrete configuration with total sum 5 (e.g. the cross of five 1's in a 3×3 block) and checked that every horizontal/vertical cut leaves a part with sum ≤1. 2. From considering the cut after the first row (or first column), correctly deduced that at least one of the two boundary rows (or boundary columns) has sum ≤1 (using nonnegativity). 3. Defined the maximal i with sum of first i−1 rows ≤1 (or the analogous j for columns), and concluded from the condition that the complementary block of last 2012−i rows (resp. last 2012−j columns) has sum ≤1. (Almost) 1. Obtained the correct 5-region cover idea (first i−1 rows, last 2012−i rows, first j−1 columns, last 2012−j columns, and the single cell (i,j)) and bounded each of the four strips by 1, but did not fully justify that every cell is covered (or mishandled the boundary indices i=1 or i=2012, etc.). 2. Proved the upper bound ≤5 via the above row/column maximality argument but left one localized gap (e.g. did not justify existence of i,j from the assumption total sum >1, or forgot to bound the central cell by ≤1). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Provide an explicit construction for the $2012 \\times 2012$ grid that achieves the maximum possible sum of all numbers.\n\nConstruction requirements:\n- Output a single Python expression that evaluates to a list of lists of numbers representing the $2012 \\times 2012$ grid.\n- Each number must be in the interval $[0, 1]$.\n- For every possible division of the grid into two smaller rectangular grids by a straight line parallel to the edges, at least one of the smaller grids must have the sum of all its numbers not greater than $1$.\n- The sum of all numbers in the grid must be exactly the maximum possible sum.\n- The output must be a single, valid Python expression (e.g., using list comprehensions) that evaluates directly to the target data structure.\n- Do not include any explanations, comments, print statements, assignments, or imports.\n\nOutput formatting requirements:\n- Include exactly one construction block and put ONLY the Python expression between the tags:\n<construct>\n...\n</construct>\n- Do not use markdown code blocks (like ```python). Do not put any extra text inside <construct>...</construct>.", "ref_construction": "[[1 if (i == 1 and j <= 2) or (j == 1 and i <= 2) else 0 for j in range(2012)] for i in range(2012)]", "verify_code": "import sys\nimport math\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n \n # Allow safe builtins to evaluate list comprehensions\n allowed_builtins = {\n 'range': range,\n 'len': len,\n 'min': min,\n 'max': max,\n 'sum': sum,\n 'int': int,\n 'float': float,\n 'bool': bool,\n 'list': list,\n 'tuple': tuple,\n 'zip': zip,\n 'abs': abs,\n 'round': round,\n 'enumerate': enumerate,\n 'map': map,\n 'filter': filter,\n 'any': any,\n 'all': all,\n }\n \n try:\n grid = eval(payload, {\"__builtins__\": allowed_builtins}, {})\n except Exception as e:\n print(f\"Failed to evaluate payload: {e}\")\n return\n \n if not isinstance(grid, list):\n print(\"Grid must be a list.\")\n return\n if len(grid) != 2012:\n print(f\"Grid must have exactly 2012 rows, got {len(grid)}.\")\n return\n \n for i in range(2012):\n row = grid[i]\n if not isinstance(row, list):\n print(f\"Row {i} is not a list.\")\n return\n if len(row) != 2012:\n print(f\"Row {i} must have exactly 2012 elements, got {len(row)}.\")\n return\n for j in range(2012):\n val = row[j]\n if not isinstance(val, (int, float)):\n print(f\"Element at ({i}, {j}) is not a number: {type(val).__name__}\")\n return\n if not (0 <= val <= 1):\n print(f\"Element at ({i}, {j}) is out of bounds [0, 1]: {val}\")\n return\n\n # Precalculate row sums and column sums using math.fsum for numerical stability\n row_sums = [math.fsum(row) for row in grid]\n col_sums = [math.fsum(grid[i][j] for i in range(2012)) for j in range(2012)]\n total_sum = math.fsum(row_sums)\n\n if not math.isclose(total_sum, 5.0, rel_tol=0.0, abs_tol=1e-9):\n print(f\"Total sum must be exactly 5, got {total_sum}.\")\n return\n \n # Verify horizontal division constraint\n for k in range(1, 2012):\n top_sum = math.fsum(row_sums[:k])\n bottom_sum = math.fsum(row_sums[k:])\n if top_sum > 1 + 1e-9 and bottom_sum > 1 + 1e-9:\n print(f\"Horizontal division at row {k} fails constraint: top_sum={top_sum}, bottom_sum={bottom_sum}\")\n return\n \n # Verify vertical division constraint\n for k in range(1, 2012):\n left_sum = math.fsum(col_sums[:k])\n right_sum = math.fsum(col_sums[k:])\n if left_sum > 1 + 1e-9 and right_sum > 1 + 1e-9:\n print(f\"Vertical division at column {k} fails constraint: left_sum={left_sum}, right_sum={right_sum}\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "APMO-2007-P2", "category": "Extremal Problems", "id": "APMO-2007-P2", "query": "In a faulty $5\\\\times5$ grid of $25$ lights, pressing the switch of one light changes the state (from off to on, or from on to off) of that light and all adjacent lights in its row and column. Initially, all lights are off. After pressing the switches several times, exactly one light is on. Determine all possible positions of this light that is on.", "ref_answer": "the cells at positions $(2,2), (2,4), (3,3), (4,2), (4,4)$", "ref_solution": "Let the lights be represented by a $5 \\times 5$ grid of cells $(i,j)$ for $1 \\le i, j \\le 5$. Pressing a switch at $(i,j)$ toggles the state of the light at $(i,j)$ and all its orthogonal neighbors. We want to find all cells $(r,c)$ such that there exists a sequence of presses leaving exactly the light at $(r,c)$ on, with all other lights off.\n\nFirst, we define two specific sets of cells:\n$$S_1 = \\{ (i,j) \\mid i \\in \\{1,2,4,5\\} \\text{ and } j \\in \\{1,3,5\\} \\}$$\n$$S_2 = \\{ (i,j) \\mid i \\in \\{1,3,5\\} \\text{ and } j \\in \\{1,2,4,5\\} \\}$$\nNotice that $S_2$ is the reflection of $S_1$ across the main diagonal. We claim that for any switch pressed, the number of toggled lights belonging to $S_1$ is always even. Let $N(r,c)$ be the set of cells toggled by pressing $(r,c)$ (which includes $(r,c)$ and its orthogonal neighbors). We can exhaustively check the size of $N(r,c) \\cap S_1$:\n- If $r \\in \\{1,5\\}$ and $c \\in \\{1,5\\}$, $|N(r,c) \\cap S_1| = 2$.\n- If $r \\in \\{1,5\\}$ and $c = 3$, $|N(r,c) \\cap S_1| = 2$.\n- If $r \\in \\{2,4\\}$ and $c \\in \\{1,5\\}$, $|N(r,c) \\cap S_1| = 2$.\n- If $r \\in \\{2,4\\}$ and $c = 3$, $|N(r,c) \\cap S_1| = 2$.\n- If $r = 3$ and $c \\in \\{1,5\\}$, $|N(r,c) \\cap S_1| = 2$.\n- If $r = 3$ and $c = 3$, $|N(r,c) \\cap S_1| = 2$.\n- If $c \\in \\{2,4\\}$ and $r \\in \\{1,5\\}$, $|N(r,c) \\cap S_1| = 2$.\n- If $c \\in \\{2,4\\}$ and $r \\in \\{2,4\\}$, $|N(r,c) \\cap S_1| = 2$.\n- If $c \\in \\{2,4\\}$ and $r = 3$, $|N(r,c) \\cap S_1| = 0$.\n\nIn all cases, pressing any switch changes the state of an even number of lights in $S_1$. Since initially all lights are off (so $0$ lights in $S_1$ are on), the parity of the number of lights turned on in $S_1$ is invariant and must remain even. Therefore, if exactly one light is finally on, its position cannot be in $S_1$. \n\nBy an identical symmetric argument, any switch press toggles an even number of lights in $S_2$. Thus, the single light that is finally on cannot be in $S_2$ either. \n\nThe position of the single light must therefore lie in the complement of $S_1$ and the complement of $S_2$. \nThe complement of $S_1$ is $Z_1 = \\{ (i,j) \\mid i = 3 \\text{ or } j \\in \\{2,4\\} \\}$.\nThe complement of $S_2$ is $Z_2 = \\{ (i,j) \\mid j = 3 \\text{ or } i \\in \\{2,4\\} \\}$.\nTaking the intersection $Z_1 \\cap Z_2$:\n- If $i = 3$, then for the cell to be in $Z_2$, we must have $j = 3$ (since $i \\notin \\{2,4\\}$). This gives the position $(3,3)$.\n- If $j \\in \\{2,4\\}$, then for the cell to be in $Z_2$, we must have $i \\in \\{2,4\\}$ (since $j \\neq 3$). This gives the positions $(2,2), (2,4), (4,2), (4,4)$.\n\nHence, the only possible positions for the final single light are the five cells $(2,2), (2,4), (3,3), (4,2),$ and $(4,4)$.\n\nBelow we provide explicit constructions for the middle position $(3,3)$ and the upper-right position $(2,4)$. We represent the presses as a $5 \\times 5$ matrix where a $1$ indicates the switch is pressed once, and a $0$ indicates it is not pressed.\n\nFor the middle position $(3,3)$, the construction is:\n$$ \\begin{pmatrix}\n0 & 0 & 0 & 1 & 1 \\\\\n0 & 0 & 1 & 0 & 0 \\\\\n0 & 1 & 1 & 0 & 1 \\\\\n1 & 0 & 0 & 0 & 1 \\\\\n1 & 0 & 1 & 1 & 0\n\\end{pmatrix} $$\nOne can verify that this sequence of presses toggles the light at $(3,3)$ an odd number of times (three times) and every other light an even number of times.\n\nFor the upper-right position $(2,4)$, the construction is:\n$$ \\begin{pmatrix}\n0 & 0 & 1 & 0 & 0 \\\\\n0 & 1 & 1 & 1 & 0 \\\\\n1 & 0 & 0 & 1 & 1 \\\\\n1 & 0 & 0 & 1 & 0 \\\\\n0 & 1 & 1 & 0 & 0\n\\end{pmatrix} $$\nSimilarly, this toggles the light at $(2,4)$ an odd number of times and all other lights an even number of times.\n\nFor the other three positions $(2,2), (4,4),$ and $(4,2)$, one can obtain the required switch presses by rotating the construction matrix for $(2,4)$ by $90^\\circ, 180^\\circ,$ and $270^\\circ$, respectively. \n\nThus, the possible positions of the single light that is on are exactly $(2,2), (2,4), (3,3), (4,2),$ and $(4,4)$.", "grading_guidelines": "(Partial) 1. Used a parity/invariant argument to obtain a nontrivial restriction on the final position (e.g. defined a subset of cells and proved that every press toggles an even number of lights in it, hence the final single on-light cannot lie in that subset). 2. Correctly identified at least one of the two key forbidden sets (equivalently, proved that the final on-light cannot be in all cells with i∈{1,2,4,5}, j∈{1,3,5}, or the symmetric set with i∈{1,3,5}, j∈{1,2,4,5}), even if the full classification is not finished. 3. Gave a correct explicit press pattern (or a verifiable constructive procedure) that results in exactly one light on for at least one of the five correct target cells. (Almost) 1. Correctly proved (typically via two parity invariants) that the final on-light must belong to the intersection of the two complements, yielding the candidate set {(2,2),(2,4),(3,3),(4,2),(4,4)}, but did not provide constructions showing these candidates are all attainable. 2. Gave constructions for (3,3) and one corner-adjacent candidate (e.g. (2,4)) and indicated obtaining the other three by rotations/symmetry, but left the symmetry reduction or the verification of the constructions insufficiently justified. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Find all possible positions of the single light that is on. For each possible position, determine a sequence of switch presses that achieves this state starting from all lights off.\n\nConstruction format requirements:\n- Output a single Python dictionary.\n- The keys must be all valid 0-based coordinates `(r, c)` (tuples of integers) of a light that can be the only one turned on.\n- The value for each key must be a list of 0-based coordinates `(r, c)` representing a sequence of switch presses that results in exactly that light being on.\n- Put ONLY the Python dictionary literal inside the `<construct>` block. Do not include any other text or markdown formatting.", "ref_construction": "{\n (1, 1): [(0, 1), (0, 3), (1, 0), (1, 1), (1, 3), (1, 4), (2, 3), (3, 0), (3, 1), (3, 2), (4, 1)],\n (1, 3): [(0, 1), (0, 3), (1, 0), (1, 1), (1, 3), (1, 4), (2, 1), (3, 2), (3, 3), (3, 4), (4, 3)],\n (2, 2): [(0, 3), (0, 4), (1, 2), (2, 1), (2, 2), (2, 4), (3, 0), (3, 4), (4, 0), (4, 2), (4, 3)],\n (3, 1): [(0, 1), (1, 0), (1, 1), (1, 2), (2, 3), (3, 0), (3, 1), (3, 3), (3, 4), (4, 1), (4, 3)],\n (3, 3): [(0, 3), (1, 2), (1, 3), (1, 4), (2, 1), (3, 0), (3, 1), (3, 3), (3, 4), (4, 1), (4, 3)]\n}", "verify_code": "import ast\nimport sys\n\ndef verify():\n # Read full stdin\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n\n # 1. Parse using ast.literal_eval\n try:\n data = ast.literal_eval(payload)\n except Exception as e:\n print(f\"Failed to parse input as Python literal: {e}\")\n return\n\n # Verify it's a dictionary\n if not isinstance(data, dict):\n print(\"Input must be a Python dictionary.\")\n return\n\n # 2. Verify keys\n expected_keys = {(1, 1), (1, 3), (2, 2), (3, 1), (3, 3)}\n if set(data.keys()) != expected_keys:\n print(f\"Dictionary keys must be exactly {expected_keys}.\")\n return\n\n # 3-7. Verify moves for each key\n for target, moves in data.items():\n if not isinstance(moves, list):\n print(f\"Value for key {target} must be a list of moves.\")\n return\n\n # 3. Initialize grid\n grid = [[False] * 5 for _ in range(5)]\n\n for move in moves:\n if not (isinstance(move, tuple) and len(move) == 2):\n print(f\"Move {move} for key {target} is not a 2-tuple.\")\n return\n r, c = move\n if type(r) is not int or type(c) is not int:\n print(f\"Move {move} for key {target} contains non-integers.\")\n return\n \n # 4. Verify bounds\n if not (0 <= r < 5 and 0 <= c < 5):\n print(f\"Move {move} for key {target} is out of bounds.\")\n return\n\n # 5. Toggle state of the cell and its valid orthogonal neighbors\n for dr, dc in [(0, 0), (-1, 0), (1, 0), (0, -1), (0, 1)]:\n nr, nc = r + dr, c + dc\n if 0 <= nr < 5 and 0 <= nc < 5:\n grid[nr][nc] = not grid[nr][nc]\n\n # 6. Count True cells\n true_cells = []\n for r in range(5):\n for c in range(5):\n if grid[r][c]:\n true_cells.append((r, c))\n\n # 7. Verify exactly one cell is True and matches target\n if len(true_cells) != 1:\n print(f\"For key {target}, expected exactly 1 light on, but found {len(true_cells)} lights on.\")\n return\n if true_cells[0] != target:\n print(f\"For key {target}, the light on is at {true_cells[0]}, which does not match the target.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "CSMO-2019-P12", "category": "Existence and Construction", "id": "CSMO-2019-P12", "query": "In a $5\\\\times5$ matrix $X$, each element is either $0$ or $1$. Consider all $5$-tuples (ordered arrays) from the rows, columns, and diagonals of $X$ (a total of $24$): $(x_{i,1},x_{i,2},\\\\cdots,x_{i,5})$, $(x_{i,5},x_{i,4},\\\\cdots,x_{i,1})$ for $i=1,2,\\\\cdots,5$; $(x_{1,j},x_{2,j},\\\\cdots,x_{5,j})$, $(x_{5,j},x_{4,j},\\\\cdots,x_{1,j})$ for $j=1,2,\\\\cdots,5$; $(x_{1,1},x_{2,2},\\\\cdots,x_{5,5})$, $(x_{5,5},x_{4,4},\\\\cdots,x_{1,1})$, $(x_{1,5},x_{2,4},\\\\cdots,x_{5,1})$, $(x_{5,1},x_{4,2},\\\\cdots,x_{1,5})$. If all these arrays are pairwise distinct, find the possible values of the sum of all elements in matrix $X$.", "ref_answer": "12 or 13", "ref_solution": "Let the set of all $24$ five-tuples in the problem be denoted by $T$. Call a five-tuple $(a,b,c,d,e)$ \"palindromic\" if $a=e$ and $b=d$. Note that for each tuple $\\alpha=(a_{1},a_{2},\\dots,a_{5})\\in T$, its reverse $\\beta=(a_{5},a_{4},\\dots,a_{1})$ is also in $T$. By the problem condition, all tuples in $T$ are distinct, so $\\alpha\\neq\\beta$, which means $\\alpha$ is not palindromic. Because the number of five-tuples with entries $0$ or $1$ that are non-palindromic is exactly $2^{5}-2^{3}=24$, $T$ is precisely the set of all non-palindromic five-tuples with entries $0$ or $1$.\n\nFor $\\alpha\\in T$, denote by $S_{\\alpha}$ the sum of the five components of $\\alpha$, and consider the total sum $\\displaystyle\\sum_{\\alpha\\in T} S_{\\alpha}$.\n\nOn the one hand, pairing each $\\alpha=(a_{1},a_{2},\\dots,a_{5})\\in T$ with its bitwise complement $\\alpha'=(1-a_{1},1-a_{2},\\dots,1-a_{5})$ shows that $\\alpha'\\in T$ and $S_{\\alpha}+S_{\\alpha'}=5$. Since the third components of $\\alpha$ and $\\alpha'$ differ, $\\alpha\\neq\\alpha'$, meaning no $\\alpha$ is paired with itself. Thus, the $24$ tuples in $T$ can be partitioned into $12$ pairs, giving $\\displaystyle\\sum_{\\alpha\\in T} S_{\\alpha} = 12 \\times 5 = 60$.\n\nOn the other hand, in the sum $\\displaystyle\\sum_{\\alpha\\in T} S_{\\alpha}$, the central element $x_{3,3}$ of $X$ is counted $8$ times, each off-center element on the two main diagonals is counted $6$ times, and each element not on the diagonals is counted $4$ times. Let $S$ be the sum of all elements of $X$. Then we can express the total sum as:\n\\[\n4x_{3,3}+2\\bigl(x_{1,1}+x_{2,2}+x_{4,4}+x_{5,5}+x_{1,5}+x_{2,4}+x_{4,2}+x_{5,1}\\bigr)+4S=60.\n\\]\nFrom this equation and the constraints on the non-palindromic tuples, it follows that the possible values for the sum $S$ of all elements in matrix $X$ are $12$ and $13$.", "grading_guidelines": "(Partial) 1. Observed that for each listed 5-tuple its reverse also appears in the list, hence every occurring 5-tuple must be non-palindromic (i.e. not equal to its reverse). 2. Counted the number of non-palindromic binary 5-tuples as 24, and concluded that the 24 arrays must be exactly the set of all non-palindromic binary 5-tuples. 3. Correctly set up a double-counting equation for \\(\\sum_{\\alpha\\in T} S_\\alpha\\) by counting how many times each entry \\(x_{i,j}\\) appears among the 24 arrays (center 8 times, other diagonal entries 6 times, off-diagonal entries 4 times), leading to a linear relation between this total and \\(S=\\sum x_{i,j}\\). 4. Computed \\(\\sum_{\\alpha\\in T} S_\\alpha=60\\) (e.g. by pairing each tuple with its bitwise complement, or by another correct global symmetry argument). (Almost) 1. Derived the correct global equation (total sum over tuples equals 60, and also equals the weighted count of matrix entries) and reduced the problem to a small finite check on the diagonal/center variables, but did not complete the final casework needed to conclude \\(S\\in\\{12,13\\}\\). 2. Correctly concluded that the 24 tuples are exactly all non-palindromic binary 5-tuples and that \\(\\sum_{\\alpha\\in T} S_\\alpha=60\\), and obtained a near-final formula giving \\(S\\) up to an unresolved parity/boundary issue (e.g. mishandled the contribution of \\(x_{3,3}\\) or one diagonal cell), so the final set of possible values for \\(S\\) is not fully justified. 3. Gave a complete derivation that forces \\(S=12\\) or \\(S=13\\), but provided only one explicit construction (or omitted verifying that both values are attainable under the distinctness condition). 4. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For every possible valid sum of all elements in the matrix, you must provide exactly one example of a $5 \\times 5$ matrix that satisfies all the conditions.\n\nConstruction requirements:\n- Output a single Python list containing lists of strings.\n- Each inner list represents one $5 \\times 5$ matrix and must contain exactly 5 strings of length 5, consisting only of the characters '0' and '1'.\n- You must include exactly one matrix for each possible sum.\n- For each matrix, the 24 tuples extracted (rows, columns, and diagonals, in both forward and reverse directions) must be pairwise distinct.\n- Put ONLY the Python literal inside the construction block. Do not include any other text.", "ref_construction": "[[\"10000\", \"11110\", \"11001\", \"00101\", \"11100\"], [\"01111\", \"00001\", \"00110\", \"11010\", \"00011\"]]", "verify_code": "import ast\nimport sys\n\ndef verify():\n try:\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n data = ast.literal_eval(payload)\n except Exception as e:\n print(f\"Parse error: {e}\")\n return\n\n if not isinstance(data, list):\n print(\"Output must be a Python list.\")\n return\n \n if len(data) != 2:\n print(f\"Expected exactly 2 matrices, got {len(data)}.\")\n return\n\n sums = set()\n\n for idx, M in enumerate(data):\n if not isinstance(M, list):\n print(f\"Matrix at index {idx} must be a list.\")\n return\n if len(M) != 5:\n print(f\"Matrix at index {idx} must contain exactly 5 strings.\")\n return\n \n total_sum = 0\n for row_idx, row in enumerate(M):\n if not isinstance(row, str):\n print(f\"Row {row_idx} in matrix {idx} must be a string.\")\n return\n if len(row) != 5:\n print(f\"Row {row_idx} in matrix {idx} must be of length 5.\")\n return\n if not all(c in '01' for c in row):\n print(f\"Row {row_idx} in matrix {idx} must contain only '0' and '1'.\")\n return\n total_sum += row.count('1')\n \n sums.add(total_sum)\n \n # Extract the 12 base tuples\n rows = [tuple(M[i]) for i in range(5)]\n cols = [tuple(M[i][j] for i in range(5)) for j in range(5)]\n diag1 = [tuple(M[i][i] for i in range(5))]\n diag2 = [tuple(M[i][4-i] for i in range(5))]\n \n base_tuples = rows + cols + diag1 + diag2\n \n # Generate the reversed counterparts, resulting in 24 tuples\n all_tuples = []\n for t in base_tuples:\n all_tuples.append(t)\n all_tuples.append(t[::-1])\n \n if len(set(all_tuples)) != 24:\n print(f\"Matrix at index {idx} does not have 24 pairwise distinct tuples.\")\n return\n\n if sums != {12, 13}:\n print(f\"The set of sums must be exactly {{12, 13}}, got {sums}.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "CSMO-2018-P14", "category": "Graph Theory", "id": "CSMO-2018-P14-789", "query": "\"Given an integer $m \\\\geq 2$, a conference has $3m$ delegates. Every two delegates either shake hands once or do not shake hands. For a positive integer $n \\\\leq 3m - 1$, if there exist $n$ delegates whose numbers of handshakes are $1, 2, \\\\cdots, n$ respectively, then the conference is called \\\"\"$n$-interesting\\\"\". If for every possible $n$-interesting conference, there always exist three delegates who have shaken hands pairwise, find the minimum value of $n$.\n\"", "ref_answer": "$2m+1$", "ref_solution": "Treat the delegates as vertices of a graph; if two delegates have shaken hands, draw an edge between their corresponding vertices. \n\nFirst, we show that $n \\le 2m$ is not sufficient to guarantee a triangle. Construct a bipartite graph whose vertices are partitioned into two sets $A = \\{A_1, A_2, \\dots, A_m\\}$ and $B = \\{B_1, B_2, \\dots, B_{2m}\\}$. Add edges $A_iB_j$ for all $1\\le i \\le m$ and $1 \\le j \\le 2m$ such that $i \\le j$. \nIn this graph, the degree of $B_j$ is the number of $A_i$ such that $i \\le j$, which is $\\min(m, j)$. Thus, the degrees of $B_1, B_2, \\dots, B_m$ are $1, 2, \\dots, m$, respectively. \nThe degree of $A_i$ is the number of $B_j$ such that $j \\ge i$, which is $2m - i + 1$. Thus, the degrees of $A_m, A_{m-1}, \\dots, A_1$ are $m+1, m+2, \\dots, 2m$, respectively. \nTherefore, the graph contains vertices with degrees $1, 2, \\dots, 2m$, making it $n$-interesting for any $n \\le 2m$. Since the graph is bipartite, it contains no triangles. This shows that $n$ must be strictly greater than $2m$.\n\nNow we prove that when $n=2m+1$, the graph must contain a triangle. Suppose for the sake of contradiction that there exists a $(2m+1)$-interesting graph on $3m$ vertices that contains no triangles. \nBy the definition of a $(2m+1)$-interesting graph, there exist vertices with degrees $1, 2, \\dots, 2m+1$. In particular, there exists a vertex of degree $2m+1$; without loss of generality, let this vertex be $A_1$, and let its neighbors be $B_1, B_2, \\dots, B_{2m+1}$. \nSuppose the graph contains no triangles; then the neighbors $B_1, \\dots, B_{2m+1}$ must be pairwise nonadjacent. This implies that any vertex $B_k$ can only be adjacent to vertices outside the set $\\{B_1, \\dots, B_{2m+1}\\}$. Since the total number of vertices is $3m$, the number of such available vertices is $3m - (2m+1) = m-1$. Consequently, the degree of each $B_k$ is at most $m-1$.\n\nThe $(2m+1)$-interesting condition requires the graph to have vertices with degrees $m, m+1, \\dots, 2m$, which constitute $m+1$ distinct values strictly greater than $m-1$. Since the degrees of $B_1, \\dots, B_{2m+1}$ are at most $m-1$, the vertices achieving these $m+1$ degrees must be among the remaining vertices. \nExcluding $A_1$ (which has degree $2m+1$) and its neighbors $B_1, \\dots, B_{2m+1}$, the number of remaining vertices is exactly $3m - 1 - (2m+1) = m-2$. \nHowever, it is impossible for $m-2$ vertices to cover the $m+1$ required degrees $m, m+1, \\dots, 2m$. This contradicts the graph being $(2m+1)$-interesting. \n\nHence, the graph must contain a triangle, satisfying the requirement. The minimum value of $n$ is $2m+1$.", "grading_guidelines": "(Partial) 1. Reformulated the problem in graph language (delegates = vertices, handshakes = edges) and correctly identified the goal as forcing a triangle in any triangle-free graph having degrees 1,2,...,n among its vertices. 2. Gave a correct triangle-free construction on 3m vertices which is n-interesting for all n≤2m (e.g. an explicit bipartite graph with vertices of degrees 1,2,...,2m), thereby proving n must be >2m. 3. In the n=2m+1 case, proved the key local fact: if a vertex has degree 2m+1 in a triangle-free graph, then its 2m+1 neighbors form an independent set, hence each of those neighbors has degree at most m−1. (Almost) 1. Proved the lower bound via a correct triangle-free construction for all n≤2m, and for n=2m+1 set up the contradiction using a degree-(2m+1) vertex and the bound deg(neighbor)≤m−1, but made a small counting error in the final pigeonhole step (e.g. miscounted remaining vertices or the number of required degree values). 2. Completed the n=2m+1 contradiction argument in essence (neighbors independent, too few remaining vertices to realize degrees m,m+1,...,2m), but did not fully justify one boundary case in the counting (such as treating m=2 separately or checking that the degree-2m+1 vertex is distinct from the vertices intended to realize degrees m..2m). 3. Derived that n≥2m+1 and attempted to show n=2m+1 works with the correct strategy, but left a minor gap in arguing why vertices of degrees m,m+1,...,2m cannot lie among the 2m+1 neighbors (i.e. did not explicitly use the deg≤m−1 bound to exclude them).", "instruction": "For the specific case $m = 789$, determine the maximum integer $K$ such that there exists a $K$-interesting conference where no three delegates have shaken hands pairwise. Provide an explicit construction of the handshake graph for this maximum $K$.\n\nConstruction requirements:\n- Output a single Python expression (e.g., a list comprehension) that evaluates to a $2367 \\times 2367$ adjacency matrix (a list of lists of integers) representing the handshakes between the $3m = 2367$ delegates.\n- The matrix must be symmetric, with 0s on the main diagonal and 0s or 1s elsewhere.\n- The graph must be triangle-free (no three delegates shake hands pairwise).\n- There must exist $K$ delegates whose degrees (number of handshakes) are exactly $1, 2, \\dots, K$.\n- $K$ must be the maximum possible value for $m = 789$.\n- Put ONLY the valid Python expression inside the construction block, without any markdown formatting, explanations, or assignments.", "ref_construction": "[[1 if (i < 789 and j >= i + 789) or (j < 789 and i >= j + 789) else 0 for j in range(2367)] for i in range(2367)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty payload\")\n return\n \n try:\n # Evaluate the payload directly to support list comprehensions\n M = eval(payload)\n except Exception as e:\n print(f\"Failed to evaluate payload: {e}\")\n return\n\n m = 789\n N = 3 * m # 2367\n K = 2 * m # 1578\n\n # 1 & 2. Check that M is a list of 2367 lists of length 2367, containing only 0 and 1\n if not isinstance(M, list):\n print(\"M is not a list\")\n return\n if len(M) != N:\n print(f\"M should have length {N}, got {len(M)}\")\n return\n \n for i, row in enumerate(M):\n if not isinstance(row, list):\n print(f\"Row {i} is not a list\")\n return\n if len(row) != N:\n print(f\"Row {i} should have length {N}, got {len(row)}\")\n return\n for j, val in enumerate(row):\n # Strictly check for int to reject booleans or other types\n if type(val) is not int:\n print(f\"M[{i}][{j}] is not an integer\")\n return\n if val not in (0, 1):\n print(f\"M[{i}][{j}] is not 0 or 1\")\n return\n\n # 3. Verify symmetry and 0s on the main diagonal\n for i in range(N):\n if M[i][i] != 0:\n print(f\"M[{i}][{i}] is not 0\")\n return\n for j in range(i + 1, N):\n if M[i][j] != M[j][i]:\n print(f\"M is not symmetric at ({i}, {j})\")\n return\n\n # 4 & 5. Verify the degrees\n degrees = [sum(row) for row in M]\n degree_set = set(degrees)\n \n for d in range(1, K + 1):\n if d not in degree_set:\n print(f\"Degree {d} is missing from the graph\")\n return\n\n # 6. Verify that the graph contains no triangles\n neighbors = [set() for _ in range(N)]\n for i in range(N):\n for j in range(N):\n if M[i][j] == 1:\n neighbors[i].add(j)\n \n for i in range(N):\n ni = neighbors[i]\n for j in ni:\n if i < j:\n # If the intersection of neighbors[i] and neighbors[j] is not empty, a triangle exists\n if not ni.isdisjoint(neighbors[j]):\n print(f\"Triangle found containing edge ({i}, {j})\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "CSMO-2004-P4", "category": "Extremal Problems", "id": "CSMO-2004-P4", "query": "\"Given an integer $n > 2004$. Fill the numbers $1, 2, \\\\cdots, n^2$ into an $n \\\\times n$ grid, with one number in each cell. If a cell contains a number that is greater than at least $2004$ numbers in its row and greater than at least $2004$ numbers in its column, then the cell is called an \\\"\"excellent cell\\\"\". Find the maximum possible number of excellent cells.\n\"", "ref_answer": "n(n-2004)", "ref_solution": "The maximum possible number of excellent cells is $n(n-2004)$.\n\nBy evaluating row constraints, the $2004$ smallest numbers in any given row cannot form excellent cells, restricting each row to at most $n-2004$ excellent cells and establishing the total upper bound of $n(n-2004)$.\n\nApplying the optimal assignment directly: for $1 \\le i \\le n$, mark cells in columns $i, i+1, \\dots, i+2003 \\pmod n$ of row $i$ with $\\ast$. Allocating the numbers $1, 2, \\dots, 2004n$ to the $\\ast$ cells and the remaining larger numbers to the unmarked cells guarantees that all unmarked cells strictly exceed the required threshold of $2004$ elements in both their respective rows and columns. This configuration achieves exactly $n(n-2004)$ excellent cells.", "grading_guidelines": "(Partial) 1. Proved the per-row upper bound: in any row, the 2004 smallest entries cannot be excellent, hence each row has at most n-2004 excellent cells (or an equivalent counting argument giving the same bound). 2. Proved the per-column upper bound analogously (each column has at most n-2004 excellent cells), and used it to justify an O(n^2) global upper bound (even if not simplified to n(n-2004)). 3. Gave a plausible construction scheme aiming for n(n-2004) excellent cells (e.g. selecting 2004 “small” positions in each row/column and placing small numbers there), but did not fully verify the column condition or the strict “>2004” requirement. (Almost) 1. Correctly proved the upper bound n(n-2004), but the construction is only sketched or has a small gap (e.g. not fully justifying that every non-star cell has at least 2004 smaller numbers in its column, or mishandling the cyclic shift argument). 2. Gave the cyclic-star construction (2004 marked cells per row, shifted so each column has exactly 2004 marked cells) and the intended number placement, but made a localized mistake such as using 2004 vs 2003 shifts, or failing to check the boundary case n=2005 / the strictness of inequalities; overall method would work after minor fixes. 3. Achieved the value n(n-2004) with a nearly complete proof, but left one nontrivial verification step insufficiently justified (typically: why all unmarked entries are simultaneously among the largest n-2004 in their row and among the largest n-2004 in their column).", "instruction": "For the specific case $n = 35$ and using a threshold of $24$ instead of $2004$ (i.e., a cell is \"excellent\" if its value is strictly greater than at least $24$ numbers in its row and strictly greater than at least $24$ numbers in its column), provide an explicit construction of the $35 \\times 35$ grid that maximizes the number of excellent cells.\n\nConstruction requirements:\n- Output a single Python list of lists representing the $35 \\times 35$ grid.\n- The grid must contain every integer from $1$ to $1225$ exactly once.\n- The number of excellent cells in your grid must be the maximum possible for $n=35$ and threshold $24$.\n- Put ONLY the Python literal (the list of lists) inside the construction block.", "ref_construction": "[\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851],\n [852, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862],\n [863, 864, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 865, 866, 867, 868, 869, 870, 871, 872, 873],\n [874, 875, 876, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 877, 878, 879, 880, 881, 882, 883, 884],\n [885, 886, 887, 888, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 889, 890, 891, 892, 893, 894, 895],\n [896, 897, 898, 899, 900, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 901, 902, 903, 904, 905, 906],\n [907, 908, 909, 910, 911, 912, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 913, 914, 915, 916, 917],\n [918, 919, 920, 921, 922, 923, 924, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 925, 926, 927, 928],\n [929, 930, 931, 932, 933, 934, 935, 936, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 937, 938, 939],\n [940, 941, 942, 943, 944, 945, 946, 947, 948, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 949, 950],\n [951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 961],\n [962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288],\n [289, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312],\n [313, 314, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336],\n [337, 338, 339, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360],\n [361, 362, 363, 364, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384],\n [385, 386, 387, 388, 389, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408],\n [409, 410, 411, 412, 413, 414, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432],\n [433, 434, 435, 436, 437, 438, 439, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456],\n [457, 458, 459, 460, 461, 462, 463, 464, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480],\n [481, 482, 483, 484, 485, 486, 487, 488, 489, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504],\n [505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528],\n [529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552],\n [553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576],\n [577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600],\n [601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624],\n [625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 640, 641, 642, 643, 644, 645, 646, 647, 648],\n [649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 665, 666, 667, 668, 669, 670, 671, 672],\n [673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 690, 691, 692, 693, 694, 695, 696],\n [697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 715, 716, 717, 718, 719, 720],\n [721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 740, 741, 742, 743, 744],\n [745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 765, 766, 767, 768],\n [769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 790, 791, 792],\n [793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 815, 816],\n [817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 840]\n]", "verify_code": "import sys\nimport ast\n\ndef verify():\n input_text = sys.stdin.read().strip()\n if not input_text:\n print(\"Empty input.\")\n return\n \n try:\n grid = ast.literal_eval(input_text)\n except Exception as e:\n print(f\"Parse error: {e}\")\n return\n \n if not isinstance(grid, list):\n print(\"The grid must be a list of lists.\")\n return\n \n if len(grid) != 35:\n print(f\"Expected exactly 35 rows, got {len(grid)}.\")\n return\n \n elements = []\n for i, row in enumerate(grid):\n if not isinstance(row, list):\n print(f\"Row {i} is not a list.\")\n return\n if len(row) != 35:\n print(f\"Row {i} must have exactly 35 elements, got {len(row)}.\")\n return\n for j, val in enumerate(row):\n if type(val) is not int:\n print(f\"Element at row {i}, col {j} is not an integer.\")\n return\n elements.append(val)\n \n if sorted(elements) != list(range(1, 1226)):\n print(\"The grid must contain every integer from 1 to 1225 exactly once.\")\n return\n \n excellent_count = 0\n for i in range(35):\n for j in range(35):\n val = grid[i][j]\n # Count strictly smaller numbers in the same row\n row_smaller = sum(1 for c in range(35) if grid[i][c] < val)\n # Count strictly smaller numbers in the same column\n col_smaller = sum(1 for r in range(35) if grid[r][j] < val)\n \n if row_smaller >= 24 and col_smaller >= 24:\n excellent_count += 1\n \n if excellent_count != 385:\n print(f\"Expected exactly 385 excellent cells, but found {excellent_count}.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "CSMO-2004-P7", "category": "Graph Theory", "id": "CSMO-2004-P7", "query": "\"$n$ teams play a double round-robin tournament (i.e., every two teams play two matches, with each team having one home match). It is known that each team can play multiple away matches in one week (from Sunday to Saturday, seven days), but if a team has a home match in a certain week, then no away matches can be scheduled for that team in that week. If all matches can be completed within $4$ weeks, find the maximum value of $n$.\n\"", "ref_answer": "6", "ref_solution": "For $1\\le i\\le n$, let $A_i$ be the set of weeks in which the $i$-th team plays home games. According to the problem's conditions, the different sets $A_i$ must be mutually non-contained. This is because if $A_i\\subseteq A_j$, then a home game of team $i$ against team $j$ could not occur: the week of this match would have to be in $A_i$, and hence in $A_j$, meaning team $j$ would have a home game that week. This violates the condition that a team cannot play an away game in a week it has a home game.\n\nSince $A_1, A_2, \\dots, A_n$ are all subsets of the $4$ available weeks, meaning $A_i \\subseteq \\{1,2,3,4\\}$, Sperner's theorem gives the upper bound:\n$$ n \\le \\binom{4}{2} = 6 $$\n\nWhen $n=6$, the schedule can be arranged as shown in the following table, where rows represent teams, columns represent weeks, and \"$*$\" indicates that the team has a home game in that week. \n\n$$\n\\def\\arraystretch{1.5}\n\\begin{array}{|c|c|c|c|c|}\n\\hline\n\\text{Team \\textbackslash\\ Week} & 1 & 2 & 3 & 4 \\\\\n\\hline\n1 & * & * & & \\\\\n2 & * & & * & \\\\\n3 & * & & & * \\\\\n4 & & * & * & \\\\\n5 & & * & & * \\\\\n6 & & & * & * \\\\\n\\hline\n\\end{array}\n$$\n\nFor any two distinct teams $i$ and $j$, team $i$ can schedule its home game against team $j$ in the unique week that is in $A_i$ but not in $A_j$. Since each team has exactly two home weeks and their sets are distinct, there is exactly one such week for each ordered pair, allowing all matches to be successfully scheduled without violating the weekly restrictions. \n\nThus, the maximum value of $n$ is $6$.", "grading_guidelines": "(Partial) 1. Introduced the sets $A_i\\subseteq\\{1,2,3,4\\}$ of weeks in which team $i$ plays at home, and correctly derived that for any $i\\ne j$ one must have $A_i\\nsubseteq A_j$ (otherwise the match $i$ at home vs $j$ cannot be scheduled). 2. Obtained a nontrivial upper bound for $n$ from the non-containment property of the $A_i$ (e.g. by noting the family is an antichain and invoking/quoting Sperner for $4$ weeks, or by an equivalent counting argument). 3. Gave a concrete schedule pattern for some $n\\ge 5$ consistent with the rule “home week implies no away matches that week”, even if not fully justified for all ordered pairs. (Almost) 1. Correctly proved the upper bound $n\\le 6$ via Sperner’s theorem (or an equivalent antichain argument), but did not provide a working construction for $n=6$. 2. Gave the $n=6$ construction (e.g. six distinct 2-element home-week sets) and explained how to place each home match $i$ vs $j$ in a week in $A_i\\setminus A_j$, but left a minor gap in justifying existence/uniqueness of such a week for every ordered pair. 3. Presented a full-looking schedule/table for $n=6$ but failed to check a small number of pairwise constraints (e.g. one ordered pair not assigned, or one week-choice accidentally conflicts with the home/away restriction), while the main Sperner/antichain idea is correct.", "instruction": "For the maximum possible number of teams $n$, provide an explicit construction of the schedule matrix.\n\nConstruction requirements:\n- Output a single Python list of lists representing a $n \\times 4$ matrix.\n- The rows represent the n teams, and the columns represent the 4 weeks.\n- Matrix entry `M[i][j]` should be:\n - `1` if team `i` plays home matches in week `j`.\n - `0` if team `i` does not play home matches in week `j` (meaning it is available to play away).\n- The matrix must satisfy the condition that for every pair of distinct teams $(A, B)$, there is at least one week where $A$ is home (`1`) and $B$ is not (`0`), and at least one week where $B$ is home (`1`) and $A$ is not (`0`).\n- Put ONLY the Python literal matrix inside the construction block.", "ref_construction": "[[1, 1, 0, 0],\n [1, 0, 1, 0],\n [1, 0, 0, 1],\n [0, 1, 1, 0],\n [0, 1, 0, 1],\n [0, 0, 1, 1]]", "verify_code": "import sys\nimport ast\n\ndef verify():\n # Read the full input from stdin\n input_str = sys.stdin.read().strip()\n \n if not input_str:\n print(\"Error: Input is empty.\")\n return\n\n # 1. Parse the input string as a Python list of lists.\n # We use ast.literal_eval for strict parsing of Python literals.\n try:\n matrix = ast.literal_eval(input_str)\n except Exception as e:\n print(f\"Error: Failed to parse input as a Python literal. {e}\")\n return\n\n # 2. Verify that the outer list has length n (teams) and inner lists length 4 (weeks).\n if not isinstance(matrix, list):\n print(\"Error: Input must be a list.\")\n return\n \n n_teams = 6\n n_weeks = 4\n \n if len(matrix) != n_teams:\n print(f\"Error: Matrix must have {n_teams} rows (teams), found {len(matrix)}.\")\n return\n \n for r_idx, row in enumerate(matrix):\n if not isinstance(row, list):\n print(f\"Error: Row {r_idx} must be a list.\")\n return\n if len(row) != n_weeks:\n print(f\"Error: Row {r_idx} must have {n_weeks} columns (weeks), found {len(row)}.\")\n return\n \n # 3. Verify that all entries in the matrix are integers 0 or 1.\n for c_idx, val in enumerate(row):\n if val not in (0, 1):\n print(f\"Error: Matrix entry at row {r_idx}, column {c_idx} must be 0 or 1. Found {val}.\")\n return\n\n # 4. Iterate through all unique pairs of row indices (i, j) where i != j.\n # We iterate i from 0 to n-1 and j from i+1 to n-1.\n for i in range(n_teams):\n for j in range(i + 1, n_teams):\n \n # 5. Verify that there exists at least one column c1 such that row[i][c1] == 1 and row[j][c1] == 0\n # This ensures Team i can host Team j.\n i_hosts_j = False\n for w in range(n_weeks):\n if matrix[i][w] == 1 and matrix[j][w] == 0:\n i_hosts_j = True\n break\n \n if not i_hosts_j:\n print(f\"Error: Condition failed for pair ({i}, {j}). Team {i} never hosts Team {j} \"\n f\"(requires a week where Team {i} is home/1 and Team {j} is away/0).\")\n return\n\n # 6. Verify that there exists at least one column c2 such that row[j][c2] == 1 and row[i][c2] == 0\n # This ensures Team j can host Team i.\n j_hosts_i = False\n for w in range(n_weeks):\n if matrix[j][w] == 1 and matrix[i][w] == 0:\n j_hosts_i = True\n break\n \n if not j_hosts_i:\n print(f\"Error: Condition failed for pair ({i}, {j}). Team {j} never hosts Team {i} \"\n f\"(requires a week where Team {j} is home/1 and Team {i} is away/0).\")\n return\n\n # 7. If all checks pass, return True.\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "CGMO-2017-P8", "category": "Operations and Strategies", "id": "CGMO-2017-P8-10", "query": "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.", "ref_answer": "$2n^{2}-2n$", "ref_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$.\n\nFor 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:\n$$B=\\begin{pmatrix}\n1&2&\\cdots&n\\\\\nn+1&n+2&\\cdots&2n\\\\\n\\vdots&\\vdots&\\ddots&\\vdots\\\\\nn^2-n+1&n^2-n+2&\\cdots&n^2\n\\end{pmatrix}.$$\n\nWe 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$.\nWhen $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$.\nAssume the claim holds for $m-1$, and consider the case $m$.\n**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.\n**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.\n\nApplying 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.\nSimilarly, 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$.\nAt 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.\nConsequently, $A$ can be transformed into $B$ by at most $(n-1)(2n-1)+(n-1)=2n^2-2n$ transpositions.\n\nTo show that $2n^2-2n$ transpositions are necessary, consider the matrix\n$$A=\\begin{pmatrix}\nn+2&n+3&\\cdots&2n&n+1\\\\\n2n+2&2n+3&\\cdots&3n&2n+1\\\\\n\\vdots&\\vdots&\\ddots&\\vdots&\\vdots\\\\\nn^2-n+2&n^2-n+3&\\cdots&n^2&n^2-n+1\\\\\n2&3&\\cdots&n&1\n\\end{pmatrix}.$$\nLet $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$.\nA 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$.\n\nSimilarly, 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$.\nA 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$.\n\nSince 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.\n\nThus, 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).", "instruction": "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.", "ref_construction": "[[((r + 1) % 10) * 10 + ((c + 1) % 10) + 1 for c in range(10)] for r in range(10)]", "verify_code": "import sys\n\ndef fail(msg):\n print(msg)\n sys.exit(0)\n\ndef safe_eval(expr: str):\n allowed_builtins = {\n \"range\": range,\n \"len\": len,\n \"list\": list,\n \"int\": int,\n }\n env = {\"__builtins__\": allowed_builtins}\n return eval(expr, env, {})\n\ndef main():\n s = sys.stdin.read()\n if not s.strip():\n fail(\"Parsing error: empty input.\")\n try:\n obj = safe_eval(s)\n except Exception as e:\n fail(f\"Parsing error: {e}\")\n\n # Dimension/type checks\n if not isinstance(obj, list):\n fail(\"Dimensions error: top-level object is not a list.\")\n if len(obj) != 10:\n fail(f\"Dimensions error: expected 10 rows, got {len(obj)}.\")\n for i, row in enumerate(obj):\n if not isinstance(row, list):\n fail(f\"Dimensions error: row {i} is not a list.\")\n if len(row) != 10:\n fail(f\"Dimensions error: expected row {i} length 10, got {len(row)}.\")\n for j, v in enumerate(row):\n if type(v) is not int:\n fail(f\"Type error: entry at ({i},{j}) is not a strict int (got {type(v).__name__}).\")\n\n A = obj\n\n # Permutation check\n flat = [A[i][j] for i in range(10) for j in range(10)]\n expected_set = set(range(1, 101))\n got_set = set(flat)\n if got_set != expected_set:\n missing = sorted(expected_set - got_set)\n extra = sorted(got_set - expected_set)\n if missing:\n fail(f\"Permutation error: missing values (first few): {missing[:10]}\")\n if extra:\n fail(f\"Permutation error: extra values (first few): {extra[:10]}\")\n fail(\"Permutation error: entries are not exactly a permutation of 1..100.\")\n if len(flat) != len(got_set):\n # duplicates exist\n # find one duplicate\n seen = set()\n dup = None\n for v in flat:\n if v in seen:\n dup = v\n break\n seen.add(v)\n fail(f\"Permutation error: duplicate value detected ({dup}).\")\n\n # Cyclic-shift pattern check\n for i in range(10):\n for j in range(10):\n exp = 10 * ((i + 1) % 10) + ((j + 1) % 10) + 1\n if A[i][j] != exp:\n fail(\n f\"Cyclic pattern error at ({i},{j}): got {A[i][j]}, expected {exp} \"\n f\"for A[i][j]=10*((i+1)%10)+((j+1)%10)+1.\"\n )\n\n # Invariant checks: D and R\n D = 0 # number of entries in a row strictly above their target row\n R = 0 # number of entries in a column strictly left of their target column\n for i in range(10):\n for j in range(10):\n v = A[i][j]\n tr = (v - 1) // 10\n tc = (v - 1) % 10\n if i < tr:\n D += 1\n if j < tc:\n R += 1\n if D != 90:\n fail(f\"Invariant error: D should be 90, got {D}.\")\n if R != 90:\n fail(f\"Invariant error: R should be 90, got {R}.\")\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n main()"} | |
| {"split": "construction", "source": "CGMO-2015-P3", "category": "Extremal Problems", "id": "CGMO-2015-P3", "query": "Consider a $12\\\\times12$ grid where each cell is colored either black or white, such that every $3\\\\times4$ or $4\\\\times3$ subgrid contains at least one black cell. Find the minimum number of black cells required.", "ref_answer": "12", "ref_solution": "Because a $12\\times 12$ grid can be partitioned into $\\frac{12\\times 12}{3\\times 4}=12$ disjoint $3\\times 4$ subgrids, there must be at least $12$ black cells.\n\nMultiple valid configurations with exactly $12$ black cells that satisfy the requirements can be constructed. Therefore, the minimum number of black cells required is $12$.", "grading_guidelines": "(Partial) 1. Observed that the board can be tiled by disjoint 3×4 rectangles (e.g. 4 by 3 array of blocks), and concluded at least one black cell is needed in each block. 2. Gave an explicit placement pattern with 12 black cells and argued it meets the condition for all 3×4 (and/or 4×3) subgrids, but did not justify minimality. 3. Proved a weaker correct lower bound (e.g. ≥10 or ≥11) using any valid disjoint-family/covering argument, even if not sharp. (Almost) 1. Correctly proved the lower bound 12 via a partition into 12 disjoint 3×4 subgrids, but did not supply (or did not fully verify) a configuration achieving 12. 2. Gave a correct construction with 12 black cells, and a correct lower bound argument, but left a small gap such as not checking one orientation (3×4 vs 4×3) or not clearly justifying that the chosen 12 rectangles are disjoint and cover the whole board. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Provide an explicit construction for the grid that achieves this minimum number of black cells.\n\nConstruction requirements:\n- Output a single Python list of lists representing the $12 \\times 12$ grid.\n- Use the integer `0` to represent a white cell and `1` to represent a black cell.\n- Your grid must contain the minimum possible number of black cells such that every $3 \\times 4$ subgrid and every $4 \\times 3$ subgrid contains at least one black cell.\n- Put ONLY the Python literal inside the construction block.", "ref_construction": "[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]", "verify_code": "import sys\nimport ast\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n\n try:\n grid = ast.literal_eval(payload)\n except Exception as e:\n print(f\"Failed to parse python literal: {e}\")\n return\n \n if not isinstance(grid, list):\n print(\"Grid must be a list.\")\n return\n \n if len(grid) != 12:\n print(f\"Grid must have exactly 12 rows, got {len(grid)}.\")\n return\n \n for i, row in enumerate(grid):\n if not isinstance(row, list):\n print(f\"Row {i} is not a list.\")\n return\n if len(row) != 12:\n print(f\"Row {i} must have exactly 12 elements, got {len(row)}.\")\n return\n for j, val in enumerate(row):\n if type(val) is not int or val not in (0, 1):\n print(f\"Element at ({i}, {j}) is not the integer 0 or 1, got {val!r}.\")\n return\n \n total_ones = sum(sum(row) for row in grid)\n if total_ones != 12:\n print(f\"Total number of 1s must be exactly 12, got {total_ones}.\")\n return\n \n # Check 3x4 subgrids\n for r in range(10):\n for c in range(9):\n subgrid_sum = sum(grid[r+i][c+j] for i in range(3) for j in range(4))\n if subgrid_sum < 1:\n print(f\"3x4 subgrid starting at ({r}, {c}) has no black cells.\")\n return\n \n # Check 4x3 subgrids\n for r in range(9):\n for c in range(10):\n subgrid_sum = sum(grid[r+i][c+j] for i in range(4) for j in range(3))\n if subgrid_sum < 1:\n print(f\"4x3 subgrid starting at ({r}, {c}) has no black cells.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "CGMO-2007-P8", "category": "Extremal Problems", "id": "CGMO-2007-P8", "query": "$n$ chess players participate in a chess tournament, where every two players play exactly one game. It is stipulated that a win earns $1$ point, a loss earns $0$ points, and a draw earns $0.5$ points for each player. If after the tournament, for any group of $m$ players, there is always one player who has defeated the other $m-1$ players, and also one player who has lost to the other $m-1$ players, then the tournament result is said to have property $P(m)$. For a given integer $m \\\\geq 4$, find the minimum value $f(m)$ of $n$ such that for any tournament result with property $P(m)$, the scores of all $n$ players are distinct.", "ref_answer": "2m-3", "ref_solution": "First, we prove a lemma.\n\n**Lemma:** For $n \\ge m$, if the results of a tournament with $n$ players have property $P(m)$, then there must be a player who wins all his games.\n\n**Proof of the lemma:** We proceed by induction on $n$. \nWhen $n = m$, the statement follows immediately from the definition of property $P(m)$. \nAssume the statement holds for $n$, and consider a tournament of $n+1$ players. Choose any subset of $n$ players; by the induction hypothesis, there is a player among them who wins all his games within this subset. Suppose that among $A_1, A_2, \\dots, A_n$, the player $A_1$ is undefeated.\n\nNow consider the last player $A_{n+1}$ and his match against $A_1$:\n- If $A_1$ defeats $A_{n+1}$, then $A_1$ is undefeated among all $n+1$ players.\n- If $A_1$ draws with $A_{n+1}$, consider the subset of $n$ players $\\{A_1, A_2, \\dots, A_{n-1}, A_{n+1}\\}$. In this subset, $A_1$ is not undefeated because he drew with $A_{n+1}$; $A_{n+1}$ is not undefeated because he did not defeat $A_1$; and for any $k \\in \\{2, \\dots, n-1\\}$, $A_k$ is not undefeated because he lost to $A_1$. Thus, nobody in this subset is undefeated, which contradicts the induction hypothesis.\n- If $A_1$ loses to $A_{n+1}$, consider the subset of $n$ players $\\{A_1, A_3, A_4, \\dots, A_n, A_{n+1}\\}$. By the induction hypothesis, there must be an undefeated player in this subset. Since $A_1$ lost to $A_{n+1}$, and $A_3, \\dots, A_n$ all lost to $A_1$, none of $A_1, A_3, \\dots, A_n$ can be undefeated. The only possible undefeated player is $A_{n+1}$, which implies $A_{n+1}$ defeats $A_3, A_4, \\dots, A_n$. Similarly, by considering the subset $\\{A_1, A_2, A_4, \\dots, A_n, A_{n+1}\\}$, we deduce that $A_{n+1}$ defeats $A_2$. Hence, $A_{n+1}$ defeats all of $A_1, A_2, \\dots, A_n$, meaning $A_{n+1}$ is undefeated among the $n+1$ players.\n\nThus, the statement holds for $n+1$. This completes the induction and the proof of the lemma.\n\nBy a symmetric argument, one can prove: for $n \\ge m$, if the results of $n$ players have property $P(m)$, then there must be a player who loses all his games.\n\nReturning to the original problem, we first prove that when $n \\ge 2m-3$, all players' scores must be distinct. \nBy repeatedly applying the first lemma, we can order the top players:\n- There is a player $A_1$ who defeats the other $n-1$ players.\n- Removing $A_1$, the remaining $n-1$ players still satisfy property $P(m)$ (since $n-1 \\ge m$). Thus, there is a player $A_2$ who defeats all remaining $n-2$ players.\n- Continuing this process, we can extract players $A_1, A_2, \\dots, A_{n-m+1}$ such that each defeats all players below them. The extraction of $A_{n-m+1}$ is valid because the number of remaining players before his extraction is $n - (n-m) = m$, which is sufficient to apply the lemma.\n\nSimilarly, by repeatedly applying the second lemma from the bottom:\n- There is a player $A_n$ who loses to the other $n-1$ players.\n- Removing $A_n$, there is a player $A_{n-1}$ who loses to all remaining $n-2$ players.\n- Continuing this process, we can extract players $A_n, A_{n-1}, \\dots, A_{n-m+3}$ such that each loses to all players above them. The extraction of $A_{n-m+3}$ is valid because the number of remaining players before his extraction is $n - (m-3) = n - m + 3 \\ge m$ (since $n \\ge 2m-3$).\n\nThe top players extracted are $A_1, \\dots, A_{n-m+1}$ (which is $n-m+1$ players) and the bottom players extracted are $A_{n-m+3}, \\dots, A_n$ (which is $m-2$ players). The total number of extracted players is $(n-m+1) + (m-2) = n-1$. The only remaining unassigned player is $A_{n-m+2}$.\nThus, among the $n$ players $A_1, A_2, \\dots, A_n$, those with smaller indices defeat those with larger indices. Their scores are $n-1, n-2, \\dots, 1, 0$, which are all distinct.\n\nNext, we prove that when $n = 2m-4$, there exists a tournament with property $P(m)$ in which two players have the same score. \nLet the $n$ players be assigned strengths $1, 2, \\dots, m-3, m-2, m-2, m-1, \\dots, 2m-5$. Assume that a player with a numerically smaller strength defeats a player with a larger strength, and players with equal strengths draw. Thus, the two players with strength $m-2$ draw against each other, and all other matches are decisive wins or losses. Because the two players with strength $m-2$ have identical match results against all other players and draw with each other, their scores are equal.\n\nWe now verify that this tournament satisfies property $P(m)$. For any chosen group of $m$ players:\n- The number of players in the entire tournament with strength $\\ge m-2$ is $2 + ((2m-5) - (m-1) + 1) = m-1$. Thus, the chosen $m$ players cannot all have strengths $\\ge m-2$. The smallest strength $i$ in the group must satisfy $i \\le m-3$. Since there is only one player with strength $i$ in the tournament, this player is unique in the group and wins all games against the other $m-1$ players.\n- The number of players in the entire tournament with strength $\\le m-2$ is $(m-3) + 2 = m-1$. Thus, the chosen $m$ players cannot all have strengths $\\le m-2$. The largest strength $j$ in the group must satisfy $j \\ge m-1$. Since there is only one player with strength $j$ in the tournament, this player is unique in the group and loses all games against the other $m-1$ players.\n\nHence, the tournament results have property $P(m)$, but there are two players whose scores are equal. \n\nTherefore, the minimum value of $n$ is $f(m) = 2m-3$.", "grading_guidelines": "(Partial) 1. Proved (or correctly stated with proof) the key lemma: for any n\\ge m, property P(m) forces the existence of a player who defeats all other players (and/or symmetrically, a player who loses to all other players). 2. Gave the iterative removal idea: repeatedly delete an all-winning player (or all-losing player) and argued that P(m) is inherited by the remaining players as long as the remaining number is still \\ge m. 3. Constructed a nontrivial example for n=2m-4 with property P(m) where two players have equal score (e.g., a ‘strength ordering’ with exactly two equal strengths producing one draw), and verified at least one of the two required extremal conditions in every m-subset (existence of a winner-all / loser-all). (Almost) 1. Correctly proved the upper bound f(m)\\le 2m-3 by extracting a long top chain of all-winners and a long bottom chain of all-losers, but made a small counting/indexing slip (e.g., off by 1 in how many players can be extracted, or did not fully justify why the chains cover n-1 players), while the main structure is correct. 2. Correctly constructed the n=2m-4 counterexample with two equal scores and essentially checked property P(m), but left a minor gap in the verification for an arbitrary chosen m-subset (e.g., did not fully justify uniqueness of the minimal/maximal strength or missed one boundary case). 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For the specific case $m=7$, determine the largest integer $n$ for which it is possible that a tournament satisfies property $P(7)$ but the scores of the $n$ players are NOT all distinct. Provide an explicit construction of such a tournament.\n\nConstruction requirements:\n- Output a single Python list of lists representing the $n \\times n$ tournament matrix $A$.\n- $A[i][j]$ represents the points player $i$ gets against player $j$.\n- Entries must be $1$ (win), $0$ (loss), or $0.5$ (draw).\n- The diagonal $A[i][i]$ must be $0$.\n- The matrix must satisfy $A[i][j] + A[j][i] = 1$ for all $i \\neq j$.\n- The tournament must satisfy Property $P(7)$: for every subset of 7 players, there is one player who defeated the other 6 (score 1 against each), and one player who lost to the other 6 (score 0 against each).\n- The row sums (total scores) must NOT be all distinct (i.e., at least two players must have the same total score).\n- Put ONLY the Python literal matrix inside the construction block.", "ref_construction": "[[0, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 1],\n [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 0.5, 1, 1, 1, 1],\n [0, 0, 0, 0, 0.5, 0, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]", "verify_code": "import sys\nimport ast\nimport itertools\n\ndef verify():\n \"\"\"\n Verifies the construction of a 10x10 tournament matrix satisfying Property P(7)\n where the scores of the players are NOT all distinct.\n \"\"\"\n # 1. Parse the input\n try:\n input_data = sys.stdin.read().strip()\n if not input_data:\n print(\"Error: Input is empty.\")\n return\n matrix = ast.literal_eval(input_data)\n except Exception as e:\n print(f\"Error: Failed to parse input as a Python literal. {e}\")\n return\n\n # 2. Verify matrix structure and size\n if not isinstance(matrix, list):\n print(\"Error: Input must be a list of lists.\")\n return\n\n n = len(matrix)\n # Instruction implies n=10 for the \"largest integer n\" case where scores might not be distinct (m=7 -> 2m-4=10)\n if n != 10:\n print(f\"Error: Expected a 10x10 matrix, but found {n} rows.\")\n return\n\n valid_entries = {0, 0.5, 1}\n\n # 3. Verify entries, diagonal, and symmetry\n for r, row in enumerate(matrix):\n if not isinstance(row, list):\n print(f\"Error: Row {r} is not a list.\")\n return\n if len(row) != n:\n print(f\"Error: Row {r} has length {len(row)}, expected {n}.\")\n return\n \n for c, val in enumerate(row):\n if val not in valid_entries:\n print(f\"Error: Invalid entry at A[{r}][{c}]: {val}. Must be 0, 0.5, or 1.\")\n return\n \n # Diagonal check\n if r == c and val != 0:\n print(f\"Error: Diagonal entry A[{r}][{c}] must be 0.\")\n return\n\n # Symmetry check: A[i][j] + A[j][i] = 1 for i != j\n for i in range(n):\n for j in range(i + 1, n):\n val_ij = matrix[i][j]\n val_ji = matrix[j][i]\n # 0.5 + 0.5 == 1.0 (float), which equals 1 (int). Strict equality is safe here.\n if val_ij + val_ji != 1:\n print(f\"Error: Consistency violation for players {i} and {j}. A[{i}][{j}] + A[{j}][{i}] = {val_ij} + {val_ji} != 1.\")\n return\n\n # 4. Verify Property P(7)\n # For every subset of 7 players, there must be:\n # - One player who defeated all others in the subset (score 1 against them).\n # - One player who lost to all others in the subset (score 0 against them).\n m = 7\n players = range(n)\n \n for subset in itertools.combinations(players, m):\n # Check for a 'winner' in the subset\n has_winner = False\n for p in subset:\n # p is a winner if A[p][other] == 1 for all other in subset (other != p)\n if all(matrix[p][other] == 1 for other in subset if other != p):\n has_winner = True\n break\n \n if not has_winner:\n print(f\"Error: Property P(7) failed. In subset {subset}, no player defeated all other 6 players.\")\n return\n\n # Check for a 'loser' in the subset\n has_loser = False\n for p in subset:\n # p is a loser if A[p][other] == 0 for all other in subset (other != p)\n if all(matrix[p][other] == 0 for other in subset if other != p):\n has_loser = True\n break\n \n if not has_loser:\n print(f\"Error: Property P(7) failed. In subset {subset}, no player lost to all other 6 players.\")\n return\n\n # 5. Calculate scores\n scores = [sum(row) for row in matrix]\n\n # 6. Verify scores are NOT all distinct\n if len(set(scores)) == n:\n print(f\"Error: All {n} players have distinct scores: {sorted(scores)}. The construction requires that at least two players have the same score.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "IMOSLC-2023-P1", "category": "Operations and Strategies", "id": "IMOSLC-2023-P1", "query": "\"Let $m$ and $n$ be integers greater than $1$. On an $m\\\\times n$ grid, each cell contains a coin placed face down. In each operation, one may choose a $2\\\\times2$ square, flip the coins at the top-left and bottom-right corners, and flip one of the coins at the bottom-left or top-right corner. Determine all pairs $(m,n)$ for which it is possible to turn all coins face up after finitely many operations.\n\"", "ref_answer": "All $(m,n)$ such that $3\\mid mn$", "ref_solution": "The possible pairs are all $(m,n)$ such that $3\\mid mn$.\n\nWhen $3\\mid mn$, the $m\\times n$ grid can be partitioned into several $1\\times3$ or $3\\times1$ small rectangles. By applying a sequence of valid operations to flip the coins in a single small rectangle, all coins on the board can be turned over in a finite number of steps.\n\nIn the cell $(i,j)$, write the remainder of $i+j$ modulo $3$. For $k=0,1,2$, let $A_k$ denote the number of coins showing heads in the cells containing $k$. Initially, $A_0=A_1=A_2=0$. Because each operation simultaneously flips exactly one coin from each of the three types of cells, $A_0$, $A_1$, and $A_2$ change parity together, so the parities of $A_0$, $A_1$, and $A_2$ are always the same. If finally all coins are heads up, then the total numbers of the three types of cells in the board must have the same parity. But when $3\\nmid mn$, one type of cell has one more or one fewer than the other two types, a contradiction!\n\nIf we assign to the cell $(i,j)$ the value $x^i y^j$, then there exist polynomials $P(x,y)$ and $Q(x,y)$ such that \n\\begin{aligned}\n&P(x,y)(x+y+1)+Q(x,y)(x+y+xy)\\\\\n&\\equiv (1+x+\\cdots+x^{m-1})(1+x+\\cdots+x^{n-1})\\pmod{2}.\n\\end{aligned}", "grading_guidelines": "(Partial) 1. Introduced the 3-colouring by i+j (mod 3) and correctly observed that each move flips exactly one coin of each colour. 2. Derived a correct invariant/congruence consequence of the move, e.g. that the parities of the numbers A0,A1,A2 of heads in the three colour classes always stay equal (or an equivalent mod-2 linear invariant). 3. From the invariant, proved a necessary condition excluding some boards (e.g. showed impossibility when 3∤mn by comparing the parities of the sizes of the three colour classes in an m×n grid). (Almost) 1. Proved the necessity (3|mn) via the 3-colouring parity argument, and for sufficiency gave a valid decomposition into 1×3/3×1 blocks but did not fully justify that a single 1×3 (or 3×1) block can always be solved by legal 2×2 moves (missing an explicit sequence or a local argument). 2. Proved sufficiency by an explicit local procedure (e.g. solving a 1×3/3×1 block and tiling the board when 3|mn), but the impossibility part is left with only a sketchy/incorrect parity count for the case 3∤mn (e.g. did not fully justify the distribution of i+j mod 3 in the m×n grid). 3. Established both directions and the final condition 3|mn, but with a small gap such as not handling one boundary case in the tiling (e.g. when only one of m,n is divisible by 3) or an unverified final step in the invariant-to-contradiction argument.", "instruction": "Give, for the 12 \\times 10 grid (rows 0..11, cols 0..9), an explicit finite sequence of allowed operations that turns all coins from face-down to face-up. Output exactly one Python expression (Python-literal-friendly) that evals to a list of operations. Each operation must be a length-3 list of distinct [r,c] integer coordinates, 0-based, within the stated ranges, and must correspond to choosing some 2 \\times 2 square with top-left corner (r,c) and flipping exactly: [r,c] (top-left), [r+1,c+1] (bottom-right), and exactly one of [r+1,c] (bottom-left) or [r,c+1] (top-right). The returned operation list must achieve that after applying all operations (toggling coin state), every cell is face-up.", "ref_construction": "[op for a in range(4) for b in range(5) for op in ([[[3*a, 2*b], [3*a, 2*b+1], [3*a+1, 2*b+1]], [[3*a+1, 2*b], [3*a+2, 2*b], [3*a+2, 2*b+1]]])]", "verify_code": "import sys, ast\n\ndef fail(msg):\n print(msg)\n raise SystemExit(0)\n\ndata = sys.stdin.read()\ntry:\n tree = ast.parse(data, mode=\"eval\")\n obj = eval(compile(tree, \"<construction>\", \"eval\"), {\"__builtins__\": {}, \"range\": range}, {})\nexcept Exception as e:\n fail(f\"Parse/eval error: {e}\")\n\nif not isinstance(obj, list):\n fail(\"Top-level must be a list of operations.\")\n\nROWS, COLS = 12, 10\ngrid = [[0 for _ in range(COLS)] for _ in range(ROWS)]\n\ndef coord_to_tuple(x, op_idx, coord_idx):\n if not isinstance(x, (list, tuple)) or len(x) != 2:\n fail(f\"Operation {op_idx}: coordinate {coord_idx} must be a list/tuple of length 2.\")\n r, c = x[0], x[1]\n if not isinstance(r, int) or not isinstance(c, int):\n fail(f\"Operation {op_idx}: coordinate {coord_idx} entries must be integers.\")\n if not (0 <= r <= ROWS - 1 and 0 <= c <= COLS - 1):\n fail(f\"Operation {op_idx}: coordinate {coord_idx} out of bounds: [{r},{c}].\")\n return (r, c)\n\nfor i, op in enumerate(obj):\n if not isinstance(op, list) or len(op) != 3:\n fail(f\"Operation {i}: must be a list of length 3.\")\n\n coords = [coord_to_tuple(op[j], i, j) for j in range(3)]\n\n if len(set(coords)) != 3:\n fail(f\"Operation {i}: coordinates must be pairwise distinct.\")\n\n pts = set(coords)\n\n legal = False\n legal_rtct = None\n for (rt, ct) in pts:\n if 0 <= rt <= ROWS - 2 and 0 <= ct <= COLS - 2:\n pattern1 = {(rt, ct), (rt + 1, ct + 1), (rt, ct + 1)}\n pattern2 = {(rt, ct), (rt + 1, ct + 1), (rt + 1, ct)}\n if pts == pattern1 or pts == pattern2:\n legal = True\n legal_rtct = (rt, ct)\n break\n if not legal:\n fail(f\"Operation {i}: illegal operation; does not match required 2x2 pattern with a valid top-left.\")\n\n # Apply toggles\n for (r, c) in coords:\n grid[r][c] ^= 1\n\nbad = [(r, c) for r in range(ROWS) for c in range(COLS) if grid[r][c] == 0]\nif bad:\n preview = \", \".join([f\"[{r},{c}]\" for (r, c) in bad[:20]])\n more = \"\" if len(bad) <= 20 else f\" ... and {len(bad)-20} more\"\n fail(f\"Not all coins are face-up; face-down cells include: {preview}{more}\")\n\nprint(\"True\")"} | |
| {"split": "construction", "source": "IMOSLC-2021-P2", "category": "Extremal Problems", "id": "IMOSLC-2021-P2-100", "query": "Given an integer $n \\\\geq 3$. There are $m \\\\g We want to color the beads using $n$ colors such that in any consecutive $n + 1$ beads, all colors appear at least once. Find the largest positive integer $m$ for which this is impossible.", "ref_answer": "n^2-n-1", "ref_solution": "We claim that the largest positive integer $m$ for which such a coloring is impossible is $m = n^2-n-1$.\n\nFirst, we prove that when $m=n^{2}-n-1$, the coloring cannot be achieved. Assume for the sake of contradiction that a valid coloring exists. By the Pigeonhole Principle, there exists a color that appears at most $\\left\\lfloor\\frac{n^{2}-n-1}{n}\\right\\rfloor=n-2$ times. Let $c \\le n-2$ be the number of times this color appears. These $c$ beads divide the remaining $m-c$ beads into $c$ consecutive blocks (intervals) around the necklace. By the Pigeonhole Principle, the maximum length of such a block is at least \n$$ \\left\\lceil\\frac{m-c}{c}\\right\\rceil \\ge \\left\\lceil\\frac{m-(n-2)}{n-2}\\right\\rceil = \\left\\lceil\\frac{n^{2}-2n+1}{n-2}\\right\\rceil = \\left\\lceil n + \\frac{1}{n-2}\\right\\rceil = n+1, $$\nwhere we used the fact that $n \\ge 3$. This means there must be a consecutive block of at least $n+1$ beads without that color, which contradicts the requirement that any consecutive $n+1$ beads contain all $n$ colors. Thus, $m = n^2-n-1$ is impossible.\n\nNext, we prove that when $m \\ge n^{2}-n$, a valid coloring can always be achieved. Let $m=kn+j$, where $0\\le j\\le n-1$. Since $m \\ge n^2-n = (n-1)n$, we have $k \\ge n-1$, which implies $k \\ge j$. We divide the $m$ beads into $k$ groups as follows:\n- $k-j$ groups of length $n$, coloring each group with the sequence of colors $1, 2, 3, \\dots, n$;\n- $j$ groups of length $n+1$, coloring each group with the sequence of colors $1, 1, 2, 3, \\dots, n$.\n\nIt is easy to verify that this coloring satisfies the requirement. Since the minimum group length is $n$, any $n+1$ consecutive beads can span at most two adjacent groups. If the $n+1$ beads are entirely contained within a single group, it must be a group of length $n+1$, which is colored $1, 1, 2, \\dots, n$ and thus contains all $n$ colors. If they span two adjacent groups, they consist of the last $x$ beads of the first group and the first $y$ beads of the second group, where $x, y \\ge 1$ and $x+y = n+1$. The first group ends with the colors $n-x+1, n-x+2, \\dots, n$. The second group begins with the colors $1, 2, \\dots, y$ (if its length is $n$) or $1, 1, 2, \\dots, y-1$ (if its length is $n+1$). In either case, the second group provides the colors $1, 2, \\dots, y-1$ (and also $1$ if $y=1$). Since $x+y = n+1$, we have $y-1 = n-x$. Therefore, the union of the colors from both parts contains $\\{n-x+1, \\dots, n\\} \\cup \\{1, \\dots, n-x\\}$, which is exactly the set of all $n$ colors. \n\nIn general, let $m = kn + j$, where $0 \\le j \\le n-1$; then a valid coloring is achievable if and only if $k \\ge j$.", "grading_guidelines": "(Partial) 1. Showed an upper bound by a pigeonhole/block argument: picked a least frequent color, bounded its number of occurrences by at most n−2 when m=n^2−n−1, and concluded there is a gap of at least n+1 consecutive beads missing that color, contradicting the condition. 2. Gave a workable construction idea for large m (e.g. repeating 1,2,…,n in blocks, possibly inserting one extra repeated color to make length n+1 blocks) and correctly argued that any n+1 consecutive beads lie in at most two adjacent blocks. 3. Correctly reduced the problem to writing m=kn+j (0≤j≤n−1) and stated/derived the key feasibility condition k≥j (equivalently m≥n^2−n), even if the proof or construction is incomplete. (Almost) 1. Correctly proved impossibility for m=n^2−n−1 using the least-frequent-color and longest-gap estimate, and correctly described a valid coloring for all m≥n^2−n, but left a small gap in checking the boundary/wrap-around case for the necklace (windows crossing the end/start). 2. Gave the block construction for m=kn+j with k≥j and verified the two-block window check, but made a localized counting error (floor/ceiling or off-by-one) in the impossibility part that does not affect the main strategy. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For the specific case $n=100$, output a valid coloring of a circular necklace with $m=12345$ beads using the $n$ colors, such that any consecutive $n+1$ beads contain all $n$ colors at least once. \n\nConstruction requirements:\n- Output a single Python expression that evaluates to a list of 12345 integers.\n- The integers must be from 1 to 100, representing the colors of the beads in order around the necklace.\n- The configuration must satisfy the condition that any window of 101 consecutive beads (including wrap-around) contains all 100 colors.\n- The construction must be a single, raw Python expression (e.g., using list concatenation, multiplication, and `range()`).\n- Do not include any explanations, comments, markdown formatting, assignments, or any non-expression content.\n- Put ONLY the Python expression inside the construction block.", "ref_construction": "list(range(1, 101)) * 78 + ([1] + list(range(1, 101))) * 45", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n \n try:\n # Evaluate the raw construction payload using Python's eval()\n # as requested by user intent to support list concatenation, multiplication, and range()\n beads = eval(payload)\n except Exception as e:\n print(f\"Failed to evaluate expression: {e}\")\n return\n \n if not isinstance(beads, list):\n print(\"Evaluated result is not a list.\")\n return\n \n if len(beads) != 12345:\n print(f\"List length is {len(beads)}, expected 12345.\")\n return\n \n for idx, bead in enumerate(beads):\n if not isinstance(bead, int) or isinstance(bead, bool):\n print(f\"Element at index {idx} is not an integer.\")\n return\n if not (1 <= bead <= 100):\n print(f\"Element at index {idx} is {bead}, expected between 1 and 100.\")\n return\n \n # Simulate the circular nature of the necklace by appending the first 100 elements\n extended_beads = beads + beads[:100]\n \n # Iterate over all sliding windows of length 101\n for i in range(len(beads)):\n window = extended_beads[i:i+101]\n distinct_colors = set(window)\n if len(distinct_colors) != 100:\n print(f\"Window starting at index {i} does not contain all 100 colors.\")\n return\n \n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "IMOSLC-2023-P4", "category": "Extremal Problems", "id": "IMOSLC-2023-P4-150", "query": "Given an integer $n\\\\geq2$. Paul has a $1\\\\times n^2$ strip of paper, with squares labeled $1, 2, \\\\cdots, n^2$ in order. Paul wants to cut the strip into $m$ consecutive segments such that, after translating these segments (rotation and flipping are not allowed), they can form an $n\\\\times n$ grid. In this grid, for each $1\\\\leq i,j\\\\leq n$, the number $a_{i,j}$ in the $i$-th row and $j$-th column satisfies $a_{i,j}\\\\equiv i+j-1\\\\pmod{n}$. If Paul can achieve this, find the minimum value of $m$.", "ref_answer": "2n-1", "ref_solution": "It suffices to work modulo $n$. In this case, the numbers on the tape are $1, 2, \\dots, n$ repeated $n$ times, and the target grid table is given by $a_{i,j} \\equiv i+j-1 \\pmod n$:\n$$\n\\def\\arraystretch{1.5}\n\\begin{array}{|c|c|c|c|c|}\n\\hline\n1 & 2 & \\cdots & n-1 & n \\\\ \\hline\n2 & 3 & \\cdots & n & 1 \\\\ \\hline\n\\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\ \\hline\nn & 1 & \\cdots & n-2 & n-1 \\\\ \\hline\n\\end{array}\n$$\n\n**Construction for $m = 2n-1$:**\nCut the tape into $2n-1$ pieces whose lengths, in order, are $n, 1, n-1, 2, n-2, \\dots, n-1, 1$. \nSpecifically, the first piece has length $n$. For $2 \\le i \\le n$, the $(2i-2)$-th piece has length $i-1$ and the $(2i-1)$-th piece has length $n-i+1$. \n\nBecause the tape consists of repeating blocks of $1, 2, \\dots, n$, the first piece is exactly $1, 2, \\dots, n$. For $2 \\le i \\le n$, the $(2i-2)$-th piece starts at the beginning of a block and thus contains $1, 2, \\dots, i-1$, while the $(2i-1)$-th piece contains the remainder of that block, $i, i+1, \\dots, n$.\n\nUse the first piece as the first row of the grid table. For $2 \\le i \\le n$, swap the $(2i-2)$-th piece with the $(2i-1)$-th piece to form the $i$-th row of the grid table. This places $i, i+1, \\dots, n$ followed by $1, 2, \\dots, i-1$, which exactly matches the $i$-th row of the grid. Hence, this cutting satisfies the requirement.\n\n**Lower bound $m \\ge 2n-1$:**\nConstruct a directed graph $G$ whose vertices are $1, 2, \\dots, n$. For each of the $m$ segments, if the numbers on the segment are $a, a+1, \\dots, b-1 \\pmod n$, add a directed edge from $a$ to $b$. The graph $G$ has a total of $m$ edges, allowing multiple edges and loops. \n\nSince the segments are contiguous on the tape, the end of one segment is immediately followed by the start of the next segment. Thus, the sequence of $m$ segments forms a continuous walk. Since the tape starts at $1$ and ends at $n \\equiv 0 \\pmod n$, the walk starts at $1$ and ends at $1$, meaning the whole tape corresponds to an Eulerian circuit of $G$. Because the tape contains all $n$ numbers, $G$ is connected and spans all $n$ vertices.\n\nThe $i$-th row of the grid is formed by a sequence of segments that starts at $i$ and ends at $i-1 \\pmod n$. Thus, the edges corresponding to the segments of the $i$-th row form a directed cycle (or loop) in $G$ that starts and ends at vertex $i$. Since there are $n$ rows, the $m$ edges of $G$ can be partitioned into $n$ such cycles.\n\nObserve that deleting one edge from a cycle leaves a path that still connects all the vertices of that cycle. Therefore, after deleting one edge from each of the $n$ cycles corresponding to the rows, the vertex set of each cycle remains connected. Since the original graph $G$ is the connected union of these cycles, the remaining graph remains connected and spans all $n$ vertices. \n\nAt this point, the connected spanning subgraph must have at least $n-1$ edges. Since we deleted exactly $n$ edges (one from each row's cycle), the total number of edges in $G$ must be at least $n + (n-1) = 2n-1$. \n\nHence, the minimum value of $m$ is $2n-1$.", "grading_guidelines": "(Partial) 1. Gave the construction achieving m=2n-1 (e.g. cut lengths n,1,n-1,2,n-2,...,n-1,1) and correctly explained how to place the pieces row-by-row to obtain rows i,i+1,...,n,1,...,i-1 modulo n. 2. Reduced the problem to working modulo n (tape is 1,2,...,n repeated n times; target grid is the cyclic Latin square a_{i,j}≡i+j-1 (mod n)), and used this to justify that each row must be formed from a cyclic shift of 1,2,...,n. 3. Set up a valid lower-bound framework by encoding each segment as an edge a→b in a directed multigraph on {1,...,n} (where the segment reads a,a+1,...,b-1 mod n), and observed that the segments in each row correspond to a directed cycle. (Almost) 1. Proved m≥2n-1 via the directed-graph/cycle decomposition idea, and gave the construction for m=2n-1, but left a small gap in justifying that after deleting one edge from each row-cycle the remaining spanning subgraph is still connected (or equivalently that the union of the resulting paths must connect all n vertices). 2. Completed the lower bound m≥2n-1 except for a localized issue in translating the geometry of the grid into the statement that the m edges can be partitioned into n cycles (one per row), or in the argument that the graph spans all n vertices. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "For the specific case $n=150$, provide an explicit construction of the segments and their arrangement that achieves the minimum number of segments $m$.\n\nConstruction format requirements:\n- Output a single Python dictionary with two keys: `'endpoints'` and `'rows'`.\n- `'endpoints'` must be a list of strictly increasing positive integers $a_1 < a_2 < \\dots < a_m = 150^2$, representing the endpoints of the segments. The $k$-th segment contains the numbers from $a_{k-1} + 1$ to $a_k$ (with $a_0 = 0$).\n- `'rows'` must be a list of 150 lists. The $i$-th list specifies the order of segments used to form the $i$-th row of the grid. Segments are 1-indexed (i.e., $1, 2, \\dots, m$).\n- The total number of segments $m$ must be the minimum possible for $n=150$.\n- The resulting $150 \\times 150$ grid must satisfy the condition $a_{i,j} \\equiv i+j-1 \\pmod{150}$ for all $1 \\le i, j \\le 150$.\n- Put ONLY the Python expression inside the construction block. The expression will be evaluated using `eval()` to obtain the dictionary, so you may use list comprehensions to keep the output compact. Do not include any imports, assignments, or markdown formatting.", "ref_construction": "{\"endpoints\": [150] + [val for i in range(2, 151) for val in ((i-1)*150 + i - 1, i*150)], \"rows\": [[1]] + [[2*i - 1, 2*i - 2] for i in range(2, 151)]}", "verify_code": "import sys\n\ndef verify():\n raw_str = sys.stdin.read().strip()\n if not raw_str:\n print(\"Empty input\")\n return\n\n try:\n data = eval(raw_str)\n except Exception as e:\n print(f\"Failed to parse input with eval: {e}\")\n return\n\n if type(data) is not dict:\n print(\"Parsed object is not a dictionary\")\n return\n \n if set(data.keys()) != {'endpoints', 'rows'}:\n print(\"Dictionary must contain exactly the keys 'endpoints' and 'rows'\")\n return\n\n endpoints = data['endpoints']\n rows = data['rows']\n\n if type(endpoints) is not list:\n print(\"'endpoints' is not a list\")\n return\n \n if len(endpoints) != 299:\n print(f\"'endpoints' must have exactly 299 elements, got {len(endpoints)}\")\n return\n \n if endpoints[-1] != 22500:\n print(f\"The last element of 'endpoints' must be 22500, got {endpoints[-1]}\")\n return\n \n prev = 0\n for i, val in enumerate(endpoints):\n if type(val) is not int:\n print(f\"Element at index {i} in 'endpoints' is not an integer\")\n return\n if val <= prev:\n print(f\"'endpoints' must be strictly increasing positive integers, but found {prev} followed by {val}\")\n return\n prev = val\n\n if type(rows) is not list:\n print(\"'rows' is not a list\")\n return\n \n if len(rows) != 150:\n print(f\"'rows' must have exactly 150 lists, got {len(rows)}\")\n return\n \n seen_segments = set()\n for i, r in enumerate(rows, 1):\n if type(r) is not list:\n print(f\"Row {i} in 'rows' is not a list\")\n return\n for idx in r:\n if type(idx) is not int:\n print(f\"Segment index {idx} in row {i} is not an integer\")\n return\n if idx < 1 or idx > 299:\n print(f\"Segment index {idx} in row {i} is out of bounds (1 to 299)\")\n return\n if idx in seen_segments:\n print(f\"Segment index {idx} appears more than once\")\n return\n seen_segments.add(idx)\n \n if len(seen_segments) != 299:\n missing = set(range(1, 300)) - seen_segments\n print(f\"Not all segment indices from 1 to 299 are used. Missing: {missing}\")\n return\n\n segments = {}\n prev = 0\n for k, val in enumerate(endpoints, 1):\n segments[k] = list(range(prev + 1, val + 1))\n prev = val\n\n grid = []\n for i, r in enumerate(rows, 1):\n row_elements = []\n for idx in r:\n row_elements.extend(segments[idx])\n if len(row_elements) != 150:\n print(f\"Reconstructed row {i} does not have exactly 150 elements (has {len(row_elements)})\")\n return\n grid.append(row_elements)\n\n for i in range(150):\n for j in range(150):\n val = grid[i][j]\n expected = (i + 1 + j + 1 - 1) % 150\n if val % 150 != expected:\n print(f\"Grid element at row {i+1}, col {j+1} is {val}, which is {val % 150} mod 150, expected {expected}\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |
| {"split": "construction", "source": "USEMO-2022-P1", "category": "Extremal Problems", "id": "USEMO-2022-P1", "query": "A \\\"stick\\\" is a $1\\\\times k$ or $k\\\\times 1$ rectangle, where $k$ is any positive integer. Find the smallest positive integer $m$ such that a $2022\\\\times2022$ board can be partitioned into $m$ disjoint sticks, and any two sticks share at most one unit-length common edge.", "ref_answer": "2042224", "ref_solution": "Let the $2022 \\times 2022$ board be partitioned into $m$ disjoint sticks. Each stick is a rectangle of dimensions $1 \\times k$ or $k \\times 1$ for some integer $k \\ge 1$, and thus has exactly $4$ vertices. Therefore, the total number of vertices of the $m$ sticks is $4m$.\n\nWe count the number of stick vertices located at the grid points of the board.\n- **Interior points:** There are $2021^2$ grid points strictly inside the board. Consider any such interior point $P$. It is shared by $4$ unit squares. If $P$ were a vertex of $0$ sticks, the $4$ squares meeting at $P$ would be covered by sticks that pass straight through $P$. Because sticks have width $1$, this requires exactly two sticks to cover the $4$ squares (either two horizontal sticks or two vertical sticks). These two sticks would then share a boundary segment of length $2$ centered at $P$, meaning they share two unit-length common edges. This contradicts the condition that any two sticks share at most one unit-length common edge. If $P$ were a vertex of exactly $1$ stick, that stick would cover exactly $1$ of the $4$ squares meeting at $P$. The remaining $3$ squares cannot be covered by a single stick passing straight through $P$ (which would cover exactly $2$ squares), meaning at least one more stick must have a corner at $P$, making it a vertex of at least $2$ sticks. Thus, every interior point must be a vertex of at least $2$ sticks.\n- **Corner points of the board:** There are $4$ corner points of the board. Each is incident to exactly $1$ square of the board, so each must be a vertex of exactly $1$ stick.\n- **Boundary points (non-corners):** Consider the $4$ corner squares of the board. Each is covered by some stick. Since a stick has width $1$ and cannot extend outside the board, the stick covering a corner square must end at one or both of the boundary points adjacent to the corner. Thus, among the two boundary points adjacent to any corner of the board, at least one is a vertex of this stick. Because a non-corner boundary point is incident to exactly $2$ squares of the board, any stick vertex at this point must be paired with another stick vertex (a stick cannot pass straight through the boundary and exit the board). Thus, this point is a vertex of exactly $2$ sticks. Since the board is $2022 \\times 2022$, these $4$ boundary points (at least one for each corner) are distinct. Hence, there are at least $4$ non-corner boundary points that are vertices of exactly $2$ sticks.\n\nSumming the number of stick vertices over all grid points, we obtain:\n$$ 4m \\ge 2 \\times 2021^2 + 1 \\times 4 + 2 \\times 4 $$\n$$ 4m \\ge 2(4084441) + 4 + 8 $$\n$$ 4m \\ge 8168882 + 12 = 8168894 $$\n\nDividing by $4$ yields:\n$$ m \\ge \\frac{8168894}{4} = 2042223.5 $$\n\nSince $m$ must be an integer, we conclude that the smallest positive integer $m$ is $2042224$.", "grading_guidelines": "(Partial) 1. Introduced counting of stick corners/vertices and the identity that each stick contributes exactly 4 vertices, so total stick-vertex count is 4m. 2. Proved the key local restriction at an interior grid point P: P cannot be a vertex of 0 sticks (else two sticks must pass straight and share a length-2 boundary, violating the “at most one unit edge” condition). 3. Proved that every interior grid point must be a vertex of at least 2 sticks (ruled out “exactly 1 stick has a corner at P” by showing the remaining 3 unit squares around P cannot be covered without another corner at P). (Almost) 1. Derived the lower bound 4m ≥ 2·2021^2 + 4 + (boundary contribution), and correctly concluded m ≥ 2042224, but the argument for the needed boundary contribution (at least four non-corner boundary points that are vertices of exactly 2 sticks) is incomplete or not fully justified. 2. Carried out the full vertex-counting approach and reached m ≥ 2042223.5, but made a localized counting slip (e.g., miscounted interior points as 2022^2 or mishandled corner/boundary points), while the overall method and use of the “share at most one edge” condition are correct. 3. Solution is almost complete, but made minor mistakes which are not negligible.", "instruction": "Solve the original problem, but for a concrete 10 \\times 10 board: output exactly one explicit partition achieving the minimum possible number of sticks under the same rules. Your final answer must consist of exactly one construction enclosed in <construct>...</construct>, where the payload is a single Python expression that evals to a 10\\times 10 matrix (list of 10 lists of length 10) of integers. Equal integers denote cells belonging to the same stick; different integers denote different sticks. Each label's cells must form a single 1\\times k or k\\times 1 rectangle (k\\geq 1) and the sticks must partition the grid. Any two distinct sticks may share at most one unit-length common edge in total. The set of labels used must be exactly {1,2,\\cdots ,M} for some M, each used at least once, and M must be as small as possible for the 10×10 case.", "ref_construction": "[[6 if r == 0 and c < 8 else 7 if r == 0 else 44 if r == 9 else 1 if c == 0 else 2 if c == 2 else 3 if c == 4 else 4 if c == 6 else 5 if c == 9 else 8 + 9 * ((r - 1) // 2) + (0 if r % 2 == 1 else 4) + {1: 0, 3: 1, 5: 2, 7: 3, 8: (3 if r % 2 == 1 else 4)}[c] for c in range(10)] for r in range(10)]", "verify_code": "import sys\nimport ast\nfrom collections import defaultdict\n\ndef fail(msg):\n print(msg)\n sys.exit(0)\n\nsrc = sys.stdin.read()\n\n# 1) Evaluate payload in restricted environment\nsafe_globals = {\n \"__builtins__\": {},\n \"range\": range,\n \"list\": list,\n \"dict\": dict,\n \"set\": set,\n \"tuple\": tuple,\n \"len\": len,\n \"min\": min,\n \"max\": max,\n \"sum\": sum,\n \"abs\": abs,\n \"sorted\": sorted,\n \"enumerate\": enumerate,\n \"zip\": zip,\n}\ntry:\n tree = ast.parse(src, mode=\"eval\")\nexcept Exception as e:\n fail(f\"Parse error: {e}\")\n\ntry:\n code = compile(tree, \"<stdin>\", \"eval\")\n obj = eval(code, safe_globals, {})\nexcept Exception as e:\n fail(f\"Eval error: {e}\")\n\n# 2) Confirm 10x10 matrix of strict ints\nif not isinstance(obj, list):\n fail(\"Dimensions/type error: top-level must be a list (10 rows).\")\nif len(obj) != 10:\n fail(f\"Dimensions error: expected 10 rows, got {len(obj)}.\")\ngrid = obj\nfor r, row in enumerate(grid):\n if not isinstance(row, list):\n fail(f\"Dimensions/type error: row {r} must be a list.\")\n if len(row) != 10:\n fail(f\"Dimensions error: row {r} expected length 10, got {len(row)}.\")\n for c, v in enumerate(row):\n if type(v) is not int:\n fail(f\"Cell type error: grid[{r}][{c}] must be a strict int, got {type(v).__name__}.\")\n\n# 3) Labels must be exactly {1..44}\nlabels = set()\nfor row in grid:\n labels.update(row)\n\nif not labels:\n fail(\"Label error: no labels found.\")\nmn, mx = min(labels), max(labels)\nif mn != 1:\n fail(f\"Label set error: minimum label must be 1, got {mn}.\")\nif mx != 44:\n fail(f\"Label set error: maximum label must be 44, got {mx}.\")\nexpected = set(range(1, 45))\nmissing = sorted(expected - labels)\nextra = sorted(labels - expected)\nif missing or extra:\n if missing and extra:\n fail(f\"Label set error: missing {missing}, extra {extra}.\")\n if missing:\n fail(f\"Label set error: missing labels {missing}.\")\n fail(f\"Label set error: extra labels {extra}.\")\n\n# 4) Each label forms one stick: fills bounding box, and box is 1xk or kx1\ncoords = {t: [] for t in range(1, 45)}\nfor r in range(10):\n for c in range(10):\n coords[grid[r][c]].append((r, c))\n\nfor t in range(1, 45):\n cells = coords[t]\n if not cells:\n fail(f\"Stick error: label {t} is unused.\")\n rs = [p[0] for p in cells]\n cs = [p[1] for p in cells]\n rmin, rmax = min(rs), max(rs)\n cmin, cmax = min(cs), max(cs)\n h = rmax - rmin + 1\n w = cmax - cmin + 1\n\n if not (h == 1 or w == 1):\n fail(f\"Stick shape error: label {t} bounding box is {h}x{w}, not a 1xk or kx1 stick.\")\n\n cellset = set(cells)\n expected_box = {(rr, cc) for rr in range(rmin, rmax + 1) for cc in range(cmin, cmax + 1)}\n if cellset != expected_box:\n missing_in_box = expected_box - cellset\n extra_outside = cellset - expected_box\n if missing_in_box:\n ex = next(iter(missing_in_box))\n fail(f\"Stick fill error: label {t} does not fill its bounding box; missing cell {ex}.\")\n ex = next(iter(extra_outside))\n fail(f\"Stick fill error: label {t} has cell outside its bounding box? example {ex}.\")\n\n# 5) Any unordered label pair shares at most one unit-length common edge\nshared = defaultdict(int)\n\nfor r in range(10):\n for c in range(10):\n a = grid[r][c]\n if c + 1 < 10:\n b = grid[r][c + 1]\n if a != b:\n x, y = (a, b) if a < b else (b, a)\n shared[(x, y)] += 1\n if r + 1 < 10:\n b = grid[r + 1][c]\n if a != b:\n x, y = (a, b) if a < b else (b, a)\n shared[(x, y)] += 1\n\nfor (x, y), cnt in shared.items():\n if cnt > 1:\n fail(f\"Shared-boundary error: labels {x} and {y} share {cnt} unit edges (>1).\")\n\nprint(\"True\")"} | |
| {"split": "construction", "source": "USEMO-2021-P6", "category": "Extremal Problems", "id": "USEMO-2021-P6-448", "query": "A \\\"doughnut\\\" is a ring formed by removing an $a \\\\times b$ rectangle from the center of an $(a+2) \\\\times (b+2)$ rectangle, consisting of $2a + 2b + 4$ unit squares, where $a$ and $b$ are arbitrary positive integers. Consider an infinite grid. For each even $n \\\\geq 8$, an \\\"$n$-order bakery\\\" is a finite set $S$ of squares such that for any doughnut $B$ composed of $n$ squares, there exists a doughnut congruent to $B$ (by translation and rotation) whose squares all belong to $S$. Let $f(n)$ denote the minimum possible number of squares in an $n$-order bakery. Find the real number $\\\\alpha$ such that for all sufficiently large even $n$, we have $\\\\frac{1}{100} < \\\\frac{f(n)}{n^\\\\alpha} < 100$.", "ref_answer": "\\\\frac{3}{2}", "ref_solution": "We say that $g(n)$ is \"at least arbitrarily close\" to $h(n)$ if \n\\[\n\\lim_{n\\to\\infty}\\frac{g(n)}{h(n)}\\ge 1.\n\\] \nA similar definition gives \"at most arbitrarily close.\" Since this problem concerns only sufficiently large integers, we may work in the above sense. \n\nWe first prove that $f(n)$ is at least arbitrarily close to \n\\[\n\\frac{1}{8}n^{\\frac{3}{2}}.\n\\] \n\nCall a doughnut \"horizontal\" if its longer side lies in a row of the grid. Assume that at least half of the doughnuts in $S$ are horizontal. Because there are $\\lfloor \\frac{n}{4}-1 \\rfloor$ distinct doughnuts, there are at least $\\frac{n}{8}-1$ horizontal doughnuts. \n\nLet the longer sides of these horizontal doughnuts lie in $k$ rows of $S$. Since their shorter sides are all different, we must choose pairs of rows to form the horizontal boundaries. Thus, we have \n\\[\n\\binom{k}{2}\\ge \\frac{n}{8}-1,\n\\] \nwhich implies that $k$ is at least arbitrarily close to \n\\[\n\\frac{\\sqrt{n}}{2}.\n\\] \n\nEach longer side contains at least $\\frac{n}{4}+1$ squares of $S$, so \n\\[\nf(n)\\text{ is at least arbitrarily close to }\\frac{\\sqrt{n}}{2}\\cdot\\frac{n}{4}\n= \\frac{1}{8}n^{\\frac{3}{2}}.\n\\] \n\nWe now prove that $f(n)$ is at most arbitrarily close to $\\sqrt{2}\\,n^{\\frac{3}{2}}$. \nLet $l=\\left\\lceil\\sqrt{\\frac{n}{2}}\\right\\rceil$, and define $S$ to consist of grid squares $(x,y)$ with $1\\le x,y\\le l^{2}$ such that at least one of $x,y$ belongs to the set \n\\[\nA=\\{1,2,\\dots,l\\}\\cup\\{2l,3l,\\dots,l^{2}\\}.\n\\]\nNote that $\\{1,2,\\dots,l^{2}-1\\}\\subseteq\\{a_{1}-a_{2}\\mid a_{1},a_{2}\\in A\\}$, i.e., every integer from $1$ to $\\frac{n}{2}-1$ can be expressed as the difference of two elements of $A$. \nMoreover, each doughnut consisting of $n$ squares has its longer side containing at most $\\frac{n}{2}-1$ squares, so any such doughnut can be placed entirely inside $S$. \n\nAt this point, the number of coordinates in $\\{1, 2, \\dots, l^2\\}$ not in $A$ is $l^2 - (2l-1) = (l-1)^2$. The number of squares $(x,y)$ where neither coordinate is in $A$ is therefore $((l-1)^2)^2 = (l-1)^4$. Thus, $S$ contains exactly $l^{4}-(l-1)^{4}$ squares. Because $l^{4}-(l-1)^{4} = 4l^3 - 6l^2 + 4l - 1$, $f(n)$ is at most arbitrarily close to $4l^{3}$, i.e., $\\sqrt{2}\\,n^{\\frac{3}{2}}$. \n\nSince $f(n)$ is bounded between $\\sim \\frac{1}{8}n^{3/2}$ and $\\sim \\sqrt{2}n^{3/2}$ for large $n$, we conclude that the real number $\\alpha$ satisfying $\\frac{1}{100} < \\frac{f(n)}{n^\\alpha} < 100$ for all sufficiently large $n$ is $\\alpha = \\frac{3}{2}$.", "grading_guidelines": "(Partial) 1. Established a nontrivial lower bound of the form f(n) \\ge c\\,n^{3/2} (e.g. by counting many distinct doughnut shapes and relating them to pairs of rows/columns, obtaining a \\binom{k}{2} bound and hence k \\gg \\sqrt n). 2. Established a nontrivial upper bound of the form f(n) \\le C\\,n^{3/2} by explicitly constructing a bakery S with |S| = O(n^{3/2}) and explaining how any n-square doughnut can be translated/rotated into S. 3. Correctly reduced the problem to determining the growth exponent by proving both f(n)=\\Omega(n^{3/2}) and f(n)=O(n^{3/2}) (even with weak/unspecified constants), hence identifying \\alpha=3/2 but with major gaps in at least one direction. (Almost) 1. Proved the lower bound via the “horizontal doughnuts” counting argument (many distinct horizontal shapes; their long sides lie in k rows; need \\binom{k}{2} at least the number of shapes; conclude k\\ge(1/2+o(1))\\sqrt n; then |S|\\ge k\\cdot(n/4+O(1)) ), but made a small slip in the exact count of distinct doughnuts or the ‘at least half are horizontal’ step. 2. Gave essentially the full explicit construction with l=\\lceil\\sqrt{n/2}\\rceil and a set A so that every length \\le n/2-1 is a difference of two elements of A, and computed |S|=l^4-(l-1)^4=4l^3+O(l^2), but left a minor gap in justifying that every doughnut’s longer side length is \\le n/2-1 or in the “difference set covers all needed side-lengths” claim. 3. Completed both bounds and concluded \\alpha=3/2, but omitted a boundary case (e.g. rotations/which side is longer, or small exceptional n) or had a localized non-negligible mistake in the constant-factor estimates while the exponent argument is correct.", "instruction": "Provide an explicit construction of a bakery for $n=448$.\n\nConstruction format requirements:\n- Output a single Python list of lists of integers representing a 2D matrix of 0s and 1s.\n- The matrix can be of any size, but it must contain at most 12300 ones.\n- For every possible valid doughnut composed of exactly $n=448$ unit squares, the matrix must contain at least one congruent copy (up to translation and rotation) made entirely of 1s.\n- A doughnut is formed by removing an $a \\times b$ rectangle from the center of an $(a+2) \\times (b+2)$ rectangle, consisting of $2a + 2b + 4$ unit squares ($a, b \\ge 1$).\n\nOutput formatting requirements:\n- Include exactly one construction block and put ONLY the Python list comprehension or literal between the tags:\n<construct>\n...\n</construct>\n- Do not use markdown formatting (no ```python ... ```).\n- The payload must be a single evaluable Python expression.", "ref_construction": "[[0 if (r >= 15 and r % 15 != 14) and (c >= 15 and c % 15 != 14) else 1 for c in range(225)] for r in range(225)]", "verify_code": "import sys\n\ndef verify():\n payload = sys.stdin.read().strip()\n if not payload:\n print(\"Empty input.\")\n return\n\n try:\n # Use eval to support list comprehensions as seen in the reference construction.\n # This is necessary because ast.literal_eval does not support comprehensions.\n matrix = eval(payload)\n except Exception as e:\n print(f\"Failed to parse input: {e}\")\n return\n\n if not isinstance(matrix, list):\n print(\"Input must be a list of lists.\")\n return\n\n if len(matrix) == 0:\n print(\"Matrix cannot be empty.\")\n return\n\n num_rows = len(matrix)\n if not all(isinstance(row, list) for row in matrix):\n print(\"Input must be a list of lists.\")\n return\n\n num_cols = len(matrix[0])\n if num_cols == 0:\n print(\"Matrix rows cannot be empty.\")\n return\n\n for row in matrix:\n if len(row) != num_cols:\n print(\"Matrix must be rectangular.\")\n return\n for cell in row:\n if cell not in (0, 1):\n print(\"Matrix must contain only 0s and 1s.\")\n return\n\n total_ones = sum(sum(row) for row in matrix)\n if total_ones > 12300:\n print(f\"Matrix contains {total_ones} ones, which exceeds the maximum allowed of 12300.\")\n return\n\n # Precompute contiguous horizontal 1s to the right\n horiz = [[0] * num_cols for _ in range(num_rows)]\n for r in range(num_rows):\n cnt = 0\n for c in range(num_cols - 1, -1, -1):\n if matrix[r][c] == 1:\n cnt += 1\n else:\n cnt = 0\n horiz[r][c] = cnt\n\n # Precompute contiguous vertical 1s downwards\n vert = [[0] * num_cols for _ in range(num_rows)]\n for r in range(num_rows - 1, -1, -1):\n for c in range(num_cols):\n if matrix[r][c] == 1:\n vert[r][c] = 1 + (vert[r+1][c] if r + 1 < num_rows else 0)\n else:\n vert[r][c] = 0\n\n # Collect all coordinates of 1s to optimize the search\n ones = [(r, c) for r in range(num_rows) for c in range(num_cols) if matrix[r][c] == 1]\n\n def check_doughnut_fast(a, b):\n \"\"\"\n Checks if a doughnut of size (a+2) x (b+2) exists in the matrix.\n The top-left corner of the doughnut must be at some (r, c).\n \"\"\"\n for r, c in ones:\n if r + b + 1 < num_rows and c + a + 1 < num_cols:\n if horiz[r][c] >= a + 2 and \\\n horiz[r+b+1][c] >= a + 2 and \\\n vert[r][c] >= b + 2 and \\\n vert[r][c+a+1] >= b + 2:\n return True\n return False\n\n # Iterate through all possible integer pairs (a, b) such that a >= 1, b >= 1, and a + b = 222\n for a in range(1, 222):\n b = 222 - a\n \n # Verify that the matrix contains the corresponding doughnut.\n # We check both (a+2)x(b+2) and (b+2)x(a+2) to account for valid rotations.\n if not (check_doughnut_fast(a, b) or check_doughnut_fast(b, a)):\n print(f\"Missing doughnut for a={a}, b={b}.\")\n return\n\n print(\"True\")\n\nif __name__ == \"__main__\":\n verify()"} | |