[白俊2493号]塔


https://www.acmicpc.net/problem/2493

1.コード

import sys
from collections import defaultdict

n = int(input())
arr = list(map(int, sys.stdin.readline().rstrip().split()))
d = defaultdict(int)
answer = [0]
max_val = arr[0]
stack = [(1, max_val)]
for tower, height in enumerate(arr[1:], 2):
    if height >= max_val:
        max_val = height
        stack.clear()
        stack.append((tower, height))
    else:
        receive_tower_idx = len(stack) - 1
        while stack and stack[-1][1] <= height:
            stack.pop()
            receive_tower_idx -= 1
        stack.append((tower, height))
        d[tower] = stack[receive_tower_idx][0]
for i in range(1, n + 1):
    print(d[i], end=' ')

2.後期


stackタイプの問題では、while文をstackの最後の項目と比較する方法がよく使われます.
receive tower idx=len(stack)-値が1つ見つかれば解けます.