公式

G - Buildings 解説 by en_translator


For each \(i\), let \(J_i\) be the sequence of conforming \(j\) sorted in ascending order, so that \(H_{J_{i,1}}\lt H_{J_{i,2}}\lt H_{J_{i,3}}\lt \ldots\ \cdots (1)\) holds.

For \(i\neq N\), focus the difference between \(J_{i+1}\) and \(J_i\). \(J_i\) always contains \((i+1)\). Then, any \(j\in J_{i+1}\) with \(H_{i+1}\gt H_j\) is not contained in \(J_i\). Meanwhile, any \(j\in J_{i+1}\) with \(H_{i+1}\lt H_i\) is always contained in \(J_i\). By \((1)\), one can obtain \(J_{i+1}\) from \(J_i\) as follows:

  1. Let \(A=J_{i+1}\).
  2. While \(A\) is non-empty, repeat the following:
    • Let \(j\) be the initial element of \(A\). If \(A_{i+1}\gt A_j\), remove \(j\) from \(A\).
    • Otherwise, terminate this loop.
  3. Push \((i+1)\) to the front of \(A\).
  4. The current \(A\) is \(J_i\).

In practice, it is easier to put in and out the last element rather than the first, so it is a good idea to manage \(J_i\) in the reverse order. Now you can use a data structure like a stack. The total complexity is \(O(N)\), as each \(j\) is put in and out at most once.

n = int(input())
h = list(map(int, input().split()))
ans = [0] * n
stc = []
for i in range(n - 2, -1, -1):
    while stc and h[stc[-1]] < h[i + 1]:
        stc.pop()
    stc.append(i + 1)
    ans[i] = len(stc)
print(*ans)

投稿日時:
最終更新: