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
.
While reading row , keep a running count
of lit windows seen so far in
that row. 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)
import sys
def main() -> None:
input = sys.stdin.buffer.readline
n, q = map(int, input().split())
prefix = [[0] * (n + 1) for _ in range(n + 1)]
for y in range(1, n + 1):
row = input().strip()
running = 0
current = prefix[y]
previous = prefix[y - 1]
for x, cell in enumerate(row, start=1):
if cell == 42:
running += 1
current[x] = previous[x] + running
answers: list[str] = []
for _ in range(q):
y1, x1, y2, x2 = map(int, input().split())
lit = prefix[y2][x2]
lit -= prefix[y1 - 1][x2]
lit -= prefix[y2][x1 - 1]
lit += prefix[y1 - 1][x1 - 1]
answers.append(str(lit))
sys.stdout.write("\n".join(answers) + "\n")
if __name__ == "__main__":
main()
Comments