[Algorithm] [백준] 1874

myeonji·2022년 2월 27일
0

Algorithm

목록 보기
53/89

push는 반드시 오름차순이여야 하므로, while 문을 통해 오름차순을 지키며 push를 한다. 오름차순으로 push가 끝나면 stack이 비워질 때까지 pop을 하게 된다.

만약, stack의 제일 상단이 x가 아니라면 수열대로 pop이 될 수 없으므로 m을 False로 바꾼 뒤 break 되어 NO를 출력한다. 만약 정상적으로(break 말고) for문이 나오면 result를 출력한다.

import sys
input = sys.stdin.readline

n = int(input())

count = 0
stack = []
result = []
m = True

for _ in range(n):
    x = int(input())

    while count < x:
        count += 1
        stack.append(count)
        result.append('+')

    if stack[-1] == x:
        stack.pop()
        result.append('-')
    else:
        m = False
        break

if m == False:
    print('NO')
else:
    print('\n'.join(result))

테스트 케이스
5
1
2
5
3
4
가 안되는 이유는 3, 4 순서로 pop 을 할 수 없기 때문이다. (stack에는 3, 4 순으로 들어가 있음)

0개의 댓글