m1ndy5's coding blog

[자료구조] 백준 10828번 스택 with Python 본문

알고리즘 with python/자료구조

[자료구조] 백준 10828번 스택 with Python

정민됴 2023. 3. 20. 15:43

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

왜 이문제가 실버지..? 했는데 input()으로는 시간초과가 나는 문제였다.
input() 대신 sys.stdin.readline().rstrip() 을 사용하면 시간초과가 해결되는 문제였다.
참고로 sys.stdin.readline()을 사용하려면 import sys를 해줘야한다는 점!!

import sys

stack = []

def push(num):
    stack.append(num)

def top():
    if len(stack) == 0:
        return -1
    return stack[len(stack)-1]

def size():
    return len(stack)

def empty():
    if len(stack) == 0:
        return 1
    return 0

def pop():
    if len(stack) == 0:
        return -1
    n = stack.pop()
    return n



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

for i in range(n):
    order = sys.stdin.readline().rstrip()
    if ' ' in order:
        order, num = order.split()

    if order == 'push':
        push(num)
    elif order == 'top':
        print(top())
    elif order == 'size':
        print(size())
    elif order == 'empty':
        print(empty())
    elif order == 'pop':
        print(pop())