[ds] 백준 #1874 스택 수열

zio·2022년 2월 7일
0

Algorithm

목록 보기
4/11

문제

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

풀이

1. stack 범벅

#스택 수열
n = int(input())
num = [i for i in range(n, 0, -1)]

seq = [] #수열
oper = [] #push, pop 저장

for _ in range(n):
  seq.append(int(input()))
  
temp = list(reversed(seq))
seq = ''.join(str(_)for _ in seq)

stack1, stack2 = [], []
s = temp.pop()
stack1.append(num.pop())
oper.append("+")
while num:
  s1 = stack1.pop()
  if s != s1:
    stack1.append(s1)
    stack1.append(num.pop())
    oper.append("+")
  else:
    stack2.append(s1)
    s = temp.pop()
    oper.append("-")
    if len(stack1) == 0:
      stack1.append(num.pop())
      oper.append("+")

for i in stack1:
  oper.append("-")

reversedStack1 = list(reversed(stack1))
result = ''.join(str(_)for _ in stack2) + ''.join(str(_) for _ in reversedStack1)
#print(stack1, stack2)

if seq != result:
  print("NO")
else:
  for op in oper:
    print(op)

접근

stack 두 개를 써서 넣었다 뺐다 하면서 주어진 자연수를 다 쓸 때까지 반복함.
매칭된 스택이랑 매칭 안돼서 남은 스택 합쳐서 입력받은 스택이랑 같으면 +,- 출력 아니면 "NO" 출력함.
근데 그냥 deque로 해도 될 것 같다. 고쳐서 올려야지.

profile
🐣

0개의 댓글