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
입력 값을 한 배열에 두고 첫 번째 인덱스를 target으로 둡니다.
ex) 4 3 6 8 7 5 2 1
target = 4
스택에 1부터 n까지의 숫자를 넣으면서 스택의 마지막 부분이 target과 같은 지 확인해 줍니다.
stack -> 1 2 3 4
4 == target
target과 같다면 스택에서 마지막으로 넣은 숫자를 pop하고, target을 다음 index로 옮겨줍니다.
바뀐 스택의 마지막 부분과 target을 계속해서 비교해주면서 위의 과정을 반복합니다.
stack -> 1 2 3
target == 3
target과 더이상 일치하지 않을 경우 다음 수를 넣으면서 위의 과정을 반복합니다.
stack -> 1 2 5
target == 6
stack -> 1 2 5 6
target == 6
stack -> 1 2 5
target == 5
...
from sys import stdin
input = stdin.readline
n = int(input())
target = []
target_index = 0
current = []
result = []
for _ in range(n):
target.append(int(input()))
for ii in range(1, n+1):
current.append(ii)
result.append('+')
while current and current[-1] == target[target_index]:
current.pop()
result.append('-')
target_index += 1
print(*result, sep='\n') if not current else print('NO')