[백준] 10828번 스택 풀이

SongKS·2020년 7월 9일
0

백준 알고리즘

목록 보기
5/7

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

1.문제

2.Code

import sys

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


def pop():
    if stack:
        return stack.pop()
    else:
        return -1


def size():
    return len(stack)


def empty():
    return 0 if stack else 1


def top():
    return stack[-1] if stack else -1


A = int(sys.stdin.readline().rstrip())
stack = []

for i in range(A):
    cmd = sys.stdin.readline().rstrip().split()
    command = cmd[0]

    if command == 'push':
        push(cmd[1])
    elif command == 'pop':
        print(pop())
    elif command == 'size':
        print(size())
    elif command == 'empty':
        print(empty())
    elif command == 'top':
        print(top())

3.해석

이 문제의 핵심은 stack도 있지만 단순히 input으로 값을 읽어오면 시간 초과가 걸리는 점이다.
나만 시간 초과에 걸린거 일 수도 있다.
아래는 시간 초과에 걸린 소스를 첨부해봤다

stack = list()


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


def pop():
    if stack:
        return stack.pop()
    else:
        return -1


def size():
    return len(stack)


def empty():
    return 0 if stack else 1


def top():
    return stack[-1] if stack else -1


A = int(input())

for i in range(A):
    cmd = input()

    command = cmd.split()[0]

    if command == 'push':
        push(cmd.split()[1])
    elif command == 'pop':
        print(pop())
    elif command == 'size':
        print(size())
    elif command == 'empty':
        print(empty())
    elif command == 'top':
        print(top())

위의 정답 소스랑 다른 점은 바로 input값과 command를 읽어오는 부분이 많은 변경점(?)이 있다
기존에 단순하게 split과 input()으로 읽어온 코드는 계속 시간 초과가 떳다!
인터넷에 찾아보니 이런 글이 있었다.

sys.stdin.readline() > raw_input() > input()

으흠 그렇군 그렇군 재빠르게 소스를 수정하고 줄 단위로 읽기 때문에 마지막에 기본으로 들어가는 공백을 지우기 위한 rstrip()까지 추가하면서 돌렸더니 문제없이 돌아갔다!

profile
백엔드와 프론트, DevOps 사이에 표류하는 개발자

0개의 댓글