Official

D - 警備の配置 / Guard Placement Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

We find the maximum number of squares visible from any empty square. By determining the lengths of contiguous empty squares horizontally and computing the answer for each contiguous vertical segment of empty squares together, this problem can be solved in \(O(HW)\) time and \(O(W)\) space.

Analysis

1. The Number of Visible Squares is “Horizontal Length + Vertical Length - 1”

For an empty square \((i,j)\), consider the following values:

  • \(L_{i,j}\): The length of the contiguous segment of empty squares containing that square horizontally
  • \(V_{i,j}\): The length of the contiguous segment of empty squares containing that square vertically

The number of squares visible from this square is:

\(L_{i,j}+V_{i,j}-1\)

Since the square itself is counted in both the horizontal and vertical directions, we subtract \(1\) at the end.

For example, if the horizontal segment has length \(4\) and the vertical segment has length \(3\), the number of visible squares is \(4+3-1=6\).

2. Searching from Scratch for Every Square is Too Slow

A method that starts from every empty square and traverses up, down, left, and right until reaching an obstacle or the room’s boundary would take \(O(HW(H+W))\) time in the worst case.

For example, if \(H=1\) and all squares are empty, inspecting up to \(W\) squares horizontally from each square takes \(O(W^2)\) time in total, which will not meet the time limit.

We need a technique to avoid repeatedly inspecting the same empty segments.

3. Within a Vertical Segment, We Only Need the Maximum Horizontal Length

Consider a contiguous vertical segment of empty squares in a certain column, and let its length be \(h\).

For any square within this segment, the number of squares visible vertically is always the same, \(h\). Therefore, the maximum number of visible squares within this segment is:

\(h+\max(\text{horizontal length of each square in the segment})-1\)

For example, if the length of the vertical segment is \(3\), and the horizontal lengths of the squares in that segment from top to bottom are \(2,5,3\), the maximum value in this segment is \(3+5-1=7\).

In other words, there is no need to store information for every square; it suffices to maintain only the following information for each column:

  • The length of the currently contiguous vertical empty segment
  • The maximum horizontal length within that segment

By reading the rows from top to bottom, we can compute the answer for a vertical segment at the moment an obstacle is reached and the segment ends.

Algorithm

Prepare two arrays of length \(W\):

  • heights[j]: The length of the currently contiguous vertical empty segment in column j
  • max_widths[j]: The maximum horizontal length within that vertical segment

Initialize both with \(0\), and initialize the answer answer to \(-1\).

1. Inspect Each Row from Left to Right

Read each row from top to bottom and process it as follows:

When encountering an obstacle #:

The ongoing vertical empty segment in that column ends.

If heights[j] is positive, update answer using the maximum value for that segment:

heights[j] + max_widths[j] - 1

After that, reset both values back to \(0\).

When encountering an empty square .:

Advance to the right to extract a contiguous group of empty squares as a block. Let its length be width.

For every column k included in this horizontal segment, perform the following:

  • Increase heights[k] by \(1\)
  • Update max_widths[k] to the maximum of its current value and width

Since the number of squares visible horizontally from any square in this horizontal segment is width, this correctly updates the necessary information.

2. Process Vertical Segments Extending to the Bottom Row

After reading all rows, some vertical segments that have not yet been finalized may remain.

For each column, if heights[j] is positive, update answer with:

heights[j] + max_widths[j] - 1

3. Output the Answer

Since we find the maximum value for every vertical empty segment, the overall maximum among them is the answer for the entire room.

If there are no empty squares at all, no updates will occur, and the initial value of \(-1\) will be output as is.

Complexity

  • Time Complexity: \(O(HW)\)
  • Space Complexity: \(O(W)\)

In each row, we scan to find horizontal segments and update the arrays for squares in those segments. Each square is processed a constant number of times, resulting in \(O(HW)\) time in total.

We only store two arrays of length \(W\) and the current single row rather than storing the entire grid, so the space complexity is \(O(W)\).

Implementation Notes

  • Compute the answer when a vertical segment ends.
    The vertical length is not yet finalized while still in progress. Maintain the maximum horizontal length and compute the answer when reaching an obstacle or the bottom edge of the room.

  • Do not forget to handle segments extending to the bottom row.
    Because these segments are not terminated by an obstacle, they must be processed separately after reading all rows.

  • Subtract \(1\) to account for double-counting the square itself.

  • The code treats the input as byte strings.
    Indexing a line read by sys.stdin.buffer.readline() yields integers. # is 35 and . is 46, so comparisons are made against these values.

    Source Code

import sys


def main():
    readline = sys.stdin.buffer.readline
    H, W = map(int, readline().split())

    heights = [0] * W
    max_widths = [0] * W
    answer = -1

    for _ in range(H):
        row = readline().strip()
        j = 0

        while j < W:
            if row[j] == 35:  # '#'
                if heights[j]:
                    value = heights[j] + max_widths[j] - 1
                    if value > answer:
                        answer = value
                    heights[j] = 0
                    max_widths[j] = 0
                j += 1
            else:
                start = j
                while j < W and row[j] == 46:  # '.'
                    j += 1

                width = j - start
                for k in range(start, j):
                    heights[k] += 1
                    if width > max_widths[k]:
                        max_widths[k] = width

    for j in range(W):
        if heights[j]:
            value = heights[j] + max_widths[j] - 1
            if value > answer:
                answer = value

    print(answer)


if __name__ == "__main__":
    main()

This editorial was generated by gpt-6-astra-medium.

posted:
last update: