Editorial for City Lights Queries
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Build a 2D prefix-sum table where is the number of lit windows in the
rectangle from
to
.
Here, means row and
means column, matching the query format
.
Let be
if window
is lit and
otherwise. Then:
For a query rectangle , use inclusion-exclusion:
Building the table takes , and each query is answered in
, so the
total time complexity is
.
Solution (Python)
def main() -> None:
n, q = map(int, input().split())
prefix = [[0] * (n + 1) for _ in range(n + 1)]
for r in range(1, n + 1):
row = input().strip()
for c, cell in enumerate(row, start=1):
lit = 1 if cell == "*" else 0
prefix[r][c] = lit + prefix[r][c - 1] + prefix[r - 1][c] - prefix[r - 1][c - 1]
answers: list[str] = []
for _ in range(q):
r1, c1, r2, c2 = map(int, input().split())
lit = prefix[r2][c2]
lit -= prefix[r1 - 1][c2]
lit -= prefix[r2][c1 - 1]
lit += prefix[r1 - 1][c1 - 1]
answers.append(str(lit))
print("\n".join(answers))
if __name__ == "__main__":
main()
Comments