[백준] 10874 - 스택 수열 (Python)

민영·2021년 7월 22일
0

[Algorithm] 백준

목록 보기
3/31
post-thumbnail

문제

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

코드

import sys

result = [] 
stack = []
count = 1 
possible = True 

testCase = int(sys.stdin.readline())

for i in range(testCase): 
    line = int(sys.stdin.readline()) 

    if line >= count:
        while line >= count:
            stack.append(count)
            result.append("+")
            count += 1

        stack.pop()
        result.append("-")

    else:
        if line == stack[-1]:
            stack.pop()
            result.append("-")
        else:
            possible = False
            break

if possible == False:
    print("NO")
else:
    for i in result:
        print(i)

결과


정리

문제 설명

input으로 주어지는 수열(순서가 있는 숫자들)을 스택에 숫자를 넣었다 빼는 것으로 만들 수 있으면 push, pop 되는 과정을 출력하고, 만들 수 없으면 "NO"를 출력해라.

주석있는 코드

import sys

# 필요한 변수 선언
result = [] # 결과값 +, - 기록하는 리스트
stack = []
count = 1 # stack에 넣었던 최대 숫자 저장
possible = True # 가능한 수열인지 파악

testCase = int(sys.stdin.readline())

for i in range(testCase): # testCase만큼 반복
    line = int(sys.stdin.readline()) # 한줄씩 읽음

    if line >= count:
        while line >= count:
            stack.append(count)
            result.append("+")
            count += 1

        stack.pop()
        result.append("-")

    else:
        if line == stack[-1]:
            stack.pop()
            result.append("-")
        else:
            possible = False
            break

if possible == False:
    print("NO")
else:
    for i in result:
        print(i)

느낀점

문제 이해하는 것부터 오래 걸렸다.. 어떤 변수를 써서 어떻게 구현할껀지 생각하는 과정에서 필요한 변수도 많고 헷갈려서 문제 푸는 것도 오래걸렸다^^ 하핳ㅎ

profile
그날의 기록

0개의 댓글