A - 2x2 Erasing 解説 by evima
First, consider the case where \((U_i,D_i,L_i,R_i)=(1,N,1,N)\).
Let \((r_1,c_1),(r_2,c_2),\ldots,(r_K,c_K)\) be the pairs \((r,c)\) such that cells \((r,c),(r,c+1),(r+1,c),(r+1,c+1)\) are all colored white, listed in lexicographic order. Clearly, \(K\) is an upper bound for the number of operations.
Moreover, this upper bound is achievable. Specifically, for \(k=1,2,\ldots,K\) in order, choose \((r,c)=(r_k,c_k)\) and color cell \((r_k,c_k)\) black.
Based on this fact, for each query, we need to calculate how many \(2\times 2\) squares that are all colored white are contained in the given two-dimensional region. This can be computed in \(O(1)\) time per query with \(O(N^2)\) preprocessing using two-dimensional cumulative sums.
By implementing this appropriately, we can solve this problem. The time complexity is \(O(N^2 + Q)\).
Implementation Example (Python3)
n, q = map(int, input().split())
ss = [input() for _ in range(n)]
s = [[ss[i][j] == "." for j in range(n)] for i in range(n)]
a = [[0] * n for _ in range(n)]
for i in range(n - 1):
for j in range(n - 1):
a[i + 1][j + 1] = s[i][j] and s[i + 1][j] and s[i][j + 1] and s[i + 1][j + 1]
for i in range(n - 1):
for j in range(n):
a[i + 1][j] += a[i][j]
for i in range(n):
for j in range(n - 1):
a[i][j + 1] += a[i][j]
for _ in range(q):
u, d, l, r = map(int, input().split())
u, d, l, r = u - 1, d - 1, l - 1, r - 1
print(a[d][r] - a[d][l] - a[u][r] + a[u][l])
投稿日時:
最終更新: