公式

D - 警備の配置 / Guard Placement 解説 by admin 印刷ページ

Gemini 3.8 Flash (High)

Overview

Given an \(H \times W\) grid, this problem asks us to find the maximum total number of contiguous empty cells (including the cell itself) that can be seen vertically and horizontally without being blocked by obstacles. If there are no empty cells at all, output -1.

Analysis

When a guard stands on an empty cell \((i, j)\), the number of cells they can see can be decomposed into the following: - The number of contiguous empty cells in the row direction (horizontal) containing cell \((i, j)\) - The number of contiguous empty cells in the column direction (vertical) containing cell \((i, j)\)

Since cell \((i, j)\) itself is counted in both the horizontal and vertical directions, the total number of cells visible from cell \((i, j)\) is: $\(\text{(number of horizontal contiguous empty cells)} + \text{(number of vertical contiguous empty cells)} - 1\)$

Naive Approach and Its Issues

If we iterate in all four directions (up, down, left, right) from every empty cell \((i, j)\) to count the visible cells, it takes \(O(H + W)\) in the worst case for a single cell. Since there are up to \(H \times W\) cells, the overall time complexity would be \(O(HW(H + W))\). The constraints for this problem are \(H \times W \leq 10^6\), so when \(H, W \approx 1000\), the number of operations exceeds \(10^9\), resulting in Time Limit Exceeded (TLE).

Solution: Compute Lengths in Batches for Each Segment

Looking at a contiguous segment of empty cells bounded by obstacles within the same row (e.g., ... within #...#), for any cell in that segment, the number of empty cells visible horizontally is the same (namely, the length of the segment itself). The same applies to the vertical direction.

Therefore, instead of searching from each cell individually, we can significantly speed up the process by processing contiguous segments of empty cells together, row by row and column by column. 1. Scan each row from left to right, determine the lengths of contiguous segments of empty cells, and record the length for all cells within each segment. 2. Scan each column from top to bottom, determine the lengths of contiguous segments of empty cells, and update the maximum total number of visible cells for each cell.

Since each cell is visited only a constant number of times, this approach solves the problem in linear time.

Algorithm

  1. Checking for Empty Cells and Row-wise Calculation:
    • Iterate through the rows from \(0\) to \(H - 1\).
    • For each row, find each contiguous segment \([start, c)\) of ., and compute its length \(L = c - start\).
    • Assign \(L\) to the corresponding positions in the array row_len.
    • If no . is found during the scan, there are no empty cells, so output -1 and terminate.
  2. Column-wise Calculation and Updating the Maximum:
    • Iterate through the columns from \(0\) to \(W - 1\).
    • For each column, find each contiguous segment \([start, r)\) of ., and compute its length \(L = r - start\).
    • For each cell in row \(i\) (\(start \leq i < r\)) within that segment, calculate the total number of visible cells using the formula: $\(\text{number of visible cells} = \text{row\_len}[i][c] + L - 1\)$
    • Update the maximum value ans found so far.
  3. Output the Answer:
    • Output ans.

Complexity

  • Time Complexity: \(O(HW)\)
    • Every cell is visited once during the row-wise scan and once during the column-wise scan. Since the operations performed for each cell take constant time, the overall time complexity is \(O(HW)\), which runs well within the time limit for the constraint \(H \times W \leq 10^6\).
  • Space Complexity: \(O(HW)\)
    • \(O(HW)\) memory is used to store the grid strings and the array row_len for recording the row segment lengths.

Implementation Details

  • Managing the Grid with a 1D Array: In Python, creating a 2D list (list of lists) with \(10^6\) elements introduces significant overhead. Creating a 1D list of size \(H \times W\) and accessing cell \((r, c)\) via the index r * W + c is faster and more memory-efficient.

  • Using Slice Assignment: When assigning the same length \(L\) to the segment \([start, c)\) in a row, using Python’s slice assignment row_len[r_offset + start : r_offset + c] = [length] * length allows for concise and fast updates.

  • Omitting the Column-wise Array: Instead of storing column-wise lengths in an array, updating the answer immediately after computing the segment length using the values in row_len saves memory by avoiding the allocation of an extra array.

    Source Code

import sys


def main():
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    H = int(input_data[0])
    W = int(input_data[1])
    S = input_data[2:]

    row_len = [0] * (H * W)
    has_dot = False

    # 各行の連続する空きマスの長さを計算
    for r in range(H):
        row_str = S[r]
        c = 0
        r_offset = r * W
        while c < W:
            if row_str[c] == ".":
                has_dot = True
                start = c
                while c < W and row_str[c] == ".":
                    c += 1
                length = c - start
                row_len[r_offset + start : r_offset + c] = [length] * length
            else:
                c += 1

    if not has_dot:
        print(-1)
        return

    # 各列の連続する空きマスの長さを計算しつつ最大値を更新
    ans = 0
    for c in range(W):
        r = 0
        while r < H:
            if S[r][c] == ".":
                start = r
                while r < H and S[r][c] == ".":
                    r += 1
                length = r - start
                for i in range(start, r):
                    val = row_len[i * W + c] + length - 1
                    if val > ans:
                        ans = val
            else:
                r += 1

    print(ans)


if __name__ == "__main__":
    main()

This editorial was generated by gemini-3.8-flash-high.

投稿日時:
最終更新: