본문 바로가기
알고리즘/스택, 큐

[백준-실버3] 1874번 스택 수열(스택, 파이썬)

by 호리미 2022. 2. 17.

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

 

<내 코드>

- 1-N까지 반복문을 돌면서 수행

- temp에 차례대로 push해주고 ans에 '+'를 담아주었다.

- 그리고 i와 answer의 인덱스 0부터 비교를 해주었다. 이 때 temp에 원소가 있어야함.

  - 일치하면 idx를 1 증가시켜 다음 정답 리스트와 비교하도록하고, result에 temp에 있는 원소를 옮긴다.

  - 이때 pop으로 옮기므로 ans에 '-'를 추가해준다.

- 이 전에 temp에 들어 있던 값들과 정답리스트 answer을 비교해서 맨 끝과 현재 idx의 원소와 같으면

  - pop을 통해 result에 옮겨준다.

  - while문을 통해 break전까지 이전 원소들과 비교함

 

- for문이 끝나면 temp에 원소가 남아있는경우 pop을 통해 차례로 result에 넣어준다.

- 최종적으로 answer과 result가 같으면 수열을 만들수 있다는 의미로 ans를 출력한다.

- 그렇지 않은 경우 NO 출력

import sys
input = sys.stdin.readline

n = int(input())
answer = [] #정답
for _ in range(n):
    answer.append(int(input()))
    
temp = [] #1-n까지 넣을 스택
result = [] #결과 담을 스택
ans = [] #push, pop 기록할 스택
idx = 0 #인덱스 기록

for i in range(1,n+1):
    temp.append(i)
    ans.append('+')
    if i == answer[idx] and temp:
        idx+=1    
        result.append(temp.pop())
        ans.append('-')
        
    ## 이 부분 주의,,(틀렸던 부분)
    while temp:
        if temp[-1] == answer[idx]:
            result.append(temp.pop())
            ans.append('-')
            idx+=1
        else:
            break
         
        
while temp:
    result.append(temp.pop())
    ans.append('-')
    
if result == answer:
    for a in ans:
        print(a)
else:
    print('NO')