파이썬 알고리즘 문제 풀이

Baekjoon Online Judge 1874번 파이썬

gogi masidda 2023. 2. 14. 18:13

문제 링크

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

 

1874번: 스택 수열

1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.

www.acmicpc.net

 

 

정답 코드

import sys

n = int(sys.stdin.readline())
current = 1
stack = [0]
answer = []
temp = True
for i in range(n):
    target = int(sys.stdin.readline().strip())

    while current <= target:
        stack.append(current)
        answer.append('+') #current가 target보다 작거나 같으면 push 
        current += 1
    if stack[-1] == target:
        stack.pop()
        answer.append('-') #stack에 제일 최근에 들어간 숫자가 target과 같으면 pop
    else: #오름차순이 되지 않을 경우
        temp=False

if temp == False:
    print('NO')
else:
    for i in answer:
        print(i)
728x90