Coding Test/Baekjoon

[Python] 파이썬 백준(10828) 스택

파송송 2023. 3. 31. 10:45
728x90

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

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net


나의 풀이

스택 구현 문제로 

  • push X: 정수 X를 스택에 넣는 연산이다.
  • pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 스택에 들어있는 정수의 개수를 출력한다.
  • empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
  • top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.

다음을 구현해야 함

시간초과 코드

loop = int(input())
stack_list = []
for _ in range(loop):
    command = list(map(str,input().split()))
    if command[0] =='push':
        stack_list.append(command[1])
    elif command[0] == 'pop':
        if stack_list == []:
            print(-1)
        else:
            print(stack_list[-1])
            del stack_list[-1]
    elif command[0] == 'size':
        print(len(stack_list))
    elif command[0] == 'empty':
        if stack_list :
            print(0)
        else:
            print(1)
    elif command[0] == 'top':
        if stack_list:
            print(stack_list[-1])
        else:
            print(-1)

시간 초과 발생함 pop 부분을 stack_list.pop()으로 변경하였으나 똑같이 발생


해결

import sys

loop = int(sys.stdin.readline())
stack_list = []
for _ in range(loop):
    command = list(sys.stdin.readline().split())
    if command[0] =='push':
        stack_list.append(command[1])

    elif command[0] == 'pop':
        if stack_list == []:
                print(-1)
        else:
            print(stack_list[-1])
            del stack_list[-1]

    elif command[0] == 'size':
        print(len(stack_list))

    elif command[0] == 'empty':
        if stack_list :
            print(0)
        else:
            print(1)

    elif command[0] == 'top':
        if stack_list:
            print(stack_list[-1])
        else:
            print(-1)

백준에서 시간 초과가 뜨면 제일 먼저 확인해봐야 하는 것이 input()으로 변경 후 통과된 모습을 볼 수 있었다.

추가로 pop 부분 시간 비교를 해봤는데 똑같은 걸 알 수 있었다.

728x90