Let me solve this step by step.
The problem asks us to maximize the sum of MEX values over all possible subgrids in an n×n grid. Let's break down the key aspects:
-
First, let's understand what contributes to a large MEX value:
- MEX is the smallest non-negative integer not present in a set
- To get a large MEX, we need consecutive numbers starting from 0
- For example, if we have [0,1,2], MEX is 3
- If we have [0,2,3], MEX is 1
-
Key observations:
- For a subgrid to have a large MEX, it needs to contain consecutive numbers starting from 0
- Larger subgrids can potentially have larger MEX values
- We want to arrange numbers so that many subgrids contain consecutive sequences
-
Strategy:
- Place smaller numbers (starting from 0) in a way that they're likely to be included in many subgrids
- Try to keep consecutive numbers close to each other
- One approach is to place numbers in a spiral pattern, which ensures that many subgrids will contain consecutive sequences
Here's the implementation:
def solve(n):
# Create n×n grid
grid = [[0] * n for _ in range(n)]
# Fill in spiral pattern
value = 0
left, right = 0, n-1
top, bottom = 0, n-1
while value < n*n:
# Fill top row
for i in range(left, right + 1):
grid[top][i] = value
value += 1
top += 1
# Fill right column
for i in range(top, bottom + 1):
grid[i][right] = value
value += 1
right -= 1
if top <= bottom:
# Fill bottom row
for i in range(right, left - 1, -1):
grid[bottom][i] = value
value += 1
bottom -= 1
if left <= right:
# Fill left column
for i in range(bottom, top - 1, -1):
grid[i][left] = value
value += 1
left += 1
return grid
# Read number of test cases
t = int(input())
for _ in range(t):
n = int(input())
result = solve(n)
# Print result
for row in result:
print(*row)
The spiral pattern works well because:
- It keeps consecutive numbers adjacent to each other
- When taking any subgrid, there's a good chance of getting consecutive sequences
- This increases the likelihood of getting large MEX values for many subgrids
For example, in a 3×3 grid, the spiral pattern would look like:
8 4 5
6 0 1
7 2 3
This arrangement ensures that many subgrids will contain consecutive numbers starting from 0, which leads to larger MEX values. The spiral pattern is particularly effective because it creates a natural progression of numbers that works well with how subgrids are formed.