Official

K - フェンスのポスター / Fence Poster Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

The maximum height of a poster that can be placed on a contiguous range of boards is the minimum height among the boards in that range. By using a monotonic stack to examine “ranges where a certain height can be maintained”, we can find the minimum width such that the area is at least \(S\) in \(O(N)\) time.

Analysis

Fixing the Height Determines the Required Width

When placing a poster of height \(h\), the width required to achieve an area of at least \(S\) is

\(w = \left\lceil \dfrac{S}{h} \right\rceil\)

.

Therefore, if there are \(W\) consecutive boards, all with a height of at least \(h\), we can choose a range of width \(w\) from them to satisfy the condition if and only if

\(hW \ge S\)

.

For example, when \(S=17\) and \(h=4\), the required width is \(\lceil 17/4 \rceil=5\). If there are \(6\) consecutive boards of height at least \(4\), it is sufficient to place the poster across \(5\) of them, and there is no need to consider a width of \(6\) as an answer candidate.

We Only Need to Check the Heights of the Boards

The height of a poster placed on a given range can be increased up to the minimum height of the boards in that range. Increasing the height does not change the width, nor does it decrease the area.

Therefore, it is sufficient to consider the minimum board height in a range as the height of the poster.

However, enumerating all ranges would require \(O(N^2)\) operations just for the number of ranges, which will not run in time for \(N \le 5 \times 10^5\). Also, expanding the range to the left and right from each board would take \(O(N^2)\) in the worst case.

Thus, we can efficiently find the ranges where a certain height can be maintained using a monotonic stack.

Algorithm

Below, board indices are \(0\)-indexed to match the code.

1. Maintain Indices Such That Heights Are Non-Decreasing

Iterate through the boards from left to right and push their indices onto the stack.

We maintain the heights of the boards in the stack from bottom to top in non-decreasing order (i.e., ascending order allowing equal heights).

Let \(i\) be the current position and height be its height. While the board at the top of the stack is strictly higher than height, pop it from the stack.

This means that the range that can be extended to the right at that popped board’s height ends right before position \(i\).

2. Compute Candidates for the Popped Board

Let \(h\) be the height of the popped board, and let \(j\) be the index at the top of the stack immediately after popping.

At this point, the heights of all boards in the interval \([j+1,i-1]\) are at least \(h\). Therefore, the available width \(W\) for placing a poster of height \(h\) is

\(W=i-j-1\)

.

  • If \(hW<S\), the area in this range is insufficient.
  • If \(hW\ge S\), a poster can be placed with the required width \(\lceil S/h\rceil\), so we update the answer.

In the code, this corresponds to the following process:

h = a[stack.pop()]
width = i - stack[-1] - 1

if h * width >= s:
    required = (s + h - 1) // h
    answer = min(answer, required)

After finishing the popping process, push index \(i\) onto the stack.

3. Handle Boundary Cases with Sentinels

The code uses the following sentinels:

  • Append a board of height \(0\) to the end of the array.
  • Initialize the stack with [-1].

Since the heights of all actual boards are positive, processing the height \(0\) at the end ensures that all remaining boards are popped.

Furthermore, when the range extends all the way to the left end, setting \(j=-1\) allows the width to be calculated with the same formula \(i-j-1\).

When Boards Have the Same Height

Because the code compares using >, boards of equal height remain on the stack.

As a result, the interval obtained each time a board is popped is not necessarily the maximal possible range for that height. However, as boards of equal height are popped successively, wider intervals will be examined using the boards further to the left, so no necessary candidates will be missed.

Explanation of Correctness

First, any width considered as a candidate for the answer can definitely be achieved.

Indeed, we verify that there is a range of length \(W\) where all board heights are at least \(h\), and that \(hW\ge S\). Thus, choosing a sub-interval of width \(\lceil S/h\rceil\) within it ensures an area of at least \(S\).

Next, we show that we never miss the optimal width.

Let \([L,R]\) be an optimal range, \(w^*\) be its width, and \(h\) be the minimum height in this range. Since a valid poster can be placed in this range,

\(hw^*\ge S\)

holds.

Focus on the leftmost board among those with height \(h\) in this range. When this board is popped from the stack:

  • Since there is no board of height less than \(h\) in the range, the right boundary extends to at least \(R\).
  • Since all boards from \(L\) up to just before the board in focus have a height strictly greater than \(h\), the left boundary extends to \(L\) or further to the left (i.e., at most \(L\)).

Therefore, the width of the range checked at this moment is at least \(w^*\). The candidate width considered here is

\(\left\lceil \dfrac{S}{h} \right\rceil \le w^*\)

.

Since all considered candidates are achievable and a candidate less than or equal to the optimal solution is guaranteed to be checked, the obtained answer is optimal.

Complexity

  • Time complexity: \(O(N)\)
  • Space complexity: \(O(N)\)

Each board index is pushed onto the stack once and popped at most once. Therefore, even with the while loop, the total number of operations is \(O(N)\).

Implementation Notes

  • Use integer arithmetic for ceiling division.

\(\lceil S/h\rceil\) can be computed with (s + h - 1) // h, avoiding floating-point precision issues.

  • Update the answer with the minimum required width, not the width of the examined range.

width is the length of the valid range, while the candidate to minimize is required.

  • Negative indexing in Python is leveraged for sentinels.

Since \(0\) is appended to the end of the array, when the top of the stack is -1, a[-1] = 0. This sentinel will never be popped in the while loop.

  • Beware of large products.

\(hW\) can be up to \(5 \times 10^{14}\). Python handles arbitrarily large integers automatically, but a \(64\)-bit integer type is required in other languages.

  • Since the minimum possible width is \(1\), we can terminate early once the answer reaches \(1\). If no valid candidate is found by the end, output \(-1\).

    Source Code

import sys


def main():
    data = list(map(int, sys.stdin.buffer.read().split()))
    n, s = data[0], data[1]
    a = data[2:]
    del data
    a.append(0)

    stack = [-1]
    answer = n + 1

    for i, height in enumerate(a):
        while a[stack[-1]] > height:
            h = a[stack.pop()]
            width = i - stack[-1] - 1

            if h * width >= s:
                required = (s + h - 1) // h
                if required < answer:
                    answer = required
                    if answer == 1:
                        print(1)
                        return

        stack.append(i)

    print(answer if answer <= n else -1)


if __name__ == "__main__":
    main()

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

posted:
last update: