본문 바로가기
알고리즘/[python] 백준 BOJ

[python] 백준 28278 스택 2

by Alan_Kim 2023. 11. 4.
728x90
반응형

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

 

28278번: 스택 2

첫째 줄에 명령의 수 N이 주어진다. (1 ≤ N ≤ 1,000,000) 둘째 줄부터 N개 줄에 명령이 하나씩 주어진다. 출력을 요구하는 명령은 하나 이상 주어진다.

www.acmicpc.net

 

 

문제 풀이

  • 기본적인 스택 사용에 관한 문제이다.
  • 다만 문제는 시간이 걸릴 수 있다는 것이다. ($N\log{N}$)
  • sys.stdin.readline으로 속도를 신경써야한다.

 

CODE

import sys
input = sys.stdin.readline
def solution(A:list):
    if A[0] ==1:
        stack.append(A[1])
    elif A[0]==2:
        if len(stack)>0:
            print(stack.pop())
        else:
            print(-1)
    elif A[0] == 3:
        print(len(stack))
    elif A[0] == 4:
        if len(stack):
            print(0)
        else:
            print(1)
    else:
        if len(stack):
            print(stack[-1])
        else:
            print(-1)
        

if __name__=='__main__':
    n = int(input())
    stack = []
    for _ in range(n):
        A = list(map(int, input().split()))
        solution(A)
728x90
반응형

댓글