[TIL] 정글 14일차 - 22/04/10

신승준·2022년 4월 14일
0

TIL

목록 보기
8/34

파이썬 문법

tuple 형태로 index, value 받기

Q = [(pos, val) for pos, val in enumerate(list(map(int, input().split())))]

# Q = [(0, 60), (1, 50), (2, 70), (3, 80), (4, 90)]

any

if any(cur[1] < x[1] for x in Q):           # any, 1개라도 참이면
    Q.append(cur)							# 이 코드를 실행한다.

백준 문제

2493 - 탑(스택)

import sys
# sys.stdin = open('input.txt')
input = sys.stdin.readline

n = int(input())
top = list(map(int, input().split()))
stack = []
ans = [0] * n

for i in range(n):
    if stack:
        while stack:
            if stack[-1][1] > top[i]:
                ans[i] = stack[-1][0] + 1
                break
            else:
                stack.pop()
        stack.append([i, top[i]])
    else:
        ans[i] = 0
        stack.append([i, top[i]])

print(*ans)

오늘 이해하기 어려웠던 문제이다.

계속 top[i]보다 낮은 탑들이 stack에 쌓여있을 수 있기 때문에 while 문을 통해서 다 없애고 마지막에 append 해줘야한다. while문이 끝나기 전에 top[i]보다 큰 걸 만나면 곧바로 stack의 index를 ans에 저장하고 while문을 끝내어 for문의 다음 i로 가면 된다.




profile
메타몽 닮음 :) email: alohajune22@gmail.com

0개의 댓글