Source: IMO-2016-P2
Category: Existence and Construction

Problem: 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:
• In each row and column, one third of the entries are I, one third are M and one third are O; and
• 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.
Note that an $n \times n$ table has $4n − 2$ diagonals.

Answer: The answer is $n$ divisible by $9$.

Reference solution:
The answer is that $n$ must be divisible by $9$.

First, we construct a valid table for $n=9$. We can fill a $9 \times 9$ table as follows:
$$
\begin{array}{|ccc|ccc|ccc|}
\hline
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 \\
\hline
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 \\
\hline
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 \\
\hline
\end{array}
$$
This pattern can be extended to any $n$ that is a multiple of $9$ by tiling the grid with this $9 \times 9$ block.

Now 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$. 

We 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.

Consider the following sets of squares, all of which are clean by the problem statement:
1. All columns with indices congruent to $2 \pmod 3$.
2. All rows with indices congruent to $2 \pmod 3$.
3. All $4k-2$ diagonals whose lengths are multiples of $3$.

Take 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.
- 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$).
- Every other cell in the grid is covered exactly once by this union.

Since 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. 

Because 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.

Construction task:
For the smallest feasible integer $n > 0$, construct a valid $n \times n$ table satisfying the given conditions.

Requirements for the construction:
- Represent the table as a Python-literal list of lists of strings, where each string is "I", "M", or "O".
- The table must satisfy all row, column, and diagonal conditions for the chosen $n$.
- Include exactly one construction block and put ONLY the Python literal matrix between the tags:
<construct>
</construct>
- Do not use code fences. Do not put any extra text inside <construct>...</construct>.

Reference 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"]]

Verifier code:
import sys
import ast

def main():
    # Read the raw input from stdin
    try:
        input_data = sys.stdin.read().strip()
        if not input_data:
            print("Error: Empty input")
            return
        # Parse the input as a Python literal (list of lists of strings)
        matrix = ast.literal_eval(input_data)
    except Exception as e:
        print(f"Error: Could not parse input as Python literal: {e}")
        return

    # Basic structure check
    if not isinstance(matrix, list) or not all(isinstance(row, list) for row in matrix):
        print("Error: Input is not a list of lists")
        return
    
    # Smallest feasible n is 9
    n = len(matrix)
    if n != 9:
        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}")
        return
    
    # Check that all rows have length n and all entries are one of "I", "M", "O"
    for r, row in enumerate(matrix):
        if len(row) != n:
            print(f"Error: Row {r} has length {len(row)} instead of {n}")
            return
        for c, val in enumerate(row):
            if val not in ("I", "M", "O"):
                print(f"Error: Invalid character '{val}' at row {r}, column {c}")
                return

    # Row and column requirements: each letter appears n/3 times (3 times for n=9)
    target_count = n // 3
    for i in range(n):
        # Row check
        row = matrix[i]
        for letter in ("I", "M", "O"):
            if row.count(letter) != target_count:
                print(f"Error: Row {i} does not have exactly {target_count} of letter '{letter}'")
                return
        
        # Column check
        col = [matrix[j][i] for j in range(n)]
        for letter in ("I", "M", "O"):
            if col.count(letter) != target_count:
                print(f"Error: Column {i} does not have exactly {target_count} of letter '{letter}'")
                return

    # Diagonal checks: for any diagonal with length L divisible by 3, 
    # each letter must appear L/3 times.
    
    # Main-direction diagonals: cells (i, j) where i - j = k
    # k ranges from -(n-1) to (n-1)
    for k in range(-(n-1), n):
        diag = [matrix[i][i-k] for i in range(n) if 0 <= i-k < n]
        L = len(diag)
        if L % 3 == 0:
            for letter in ("I", "M", "O"):
                if diag.count(letter) != L // 3:
                    print(f"Error: Main-direction diagonal (i-j={k}) of length {L} fails the distribution rule for letter '{letter}'")
                    return

    # Anti-direction diagonals: cells (i, j) where i + j = k
    # k ranges from 0 to 2n-2
    for k in range(2 * n - 1):
        diag = [matrix[i][k-i] for i in range(n) if 0 <= k-i < n]
        L = len(diag)
        if L % 3 == 0:
            for letter in ("I", "M", "O"):
                if diag.count(letter) != L // 3:
                    print(f"Error: Anti-direction diagonal (i+j={k}) of length {L} fails the distribution rule for letter '{letter}'")
                    return

    # If all checks pass
    print("True")

if __name__ == "__main__":
    main()