[Algorithm][Python] 백준(BOJ) 10828 스택

최대 1 분 소요

[문제]

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

image

image


[내 코드]

n = int(input())

stack = []

for _ in range(n):
    order = input().split()

    if order.startswith('push'):
        s , x = order.split()
        stack.append(int(x))
    elif order == 'pop':
        if bool(stack):
            v = stack.pop()
            print(v)
        else:
             print(-1)
    elif order == "size":
        print(len(stack))
    elif order == "empty":
        print(int(not bool(stack)))
    elif order == "top":
        if bool(stack):
            print(stack[-1])
        else:
            print(-1)

반복문에서 input()으로 받으면 시간 초과가 날 수 있다는 걸 깜박했다ㅠㅠ
sys를 기본으로 쓰는 습관을 들여야겠다.

#### 해결

import sys

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

stack = []

for _ in range(n):
    order = sys.stdin.readline().strip()

    if order.startswith('push'):
        s , x = order.split()
        stack.append(int(x))
    elif order == 'pop':
        if bool(stack):
            v = stack.pop()
            print(v)
        else:
             print(-1)
    elif order == "size":
        print(len(stack))
    elif order == "empty":
        print(int(not bool(stack)))
    elif order == "top":
        if bool(stack):
            print(stack[-1])
        else:
            print(-1)

image

댓글남기기