jihyeon's Blog

2023-11-11

스택


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

파이썬으로 스택 구현

sys의 readline를 사용하지 않으면 시간 초과됨. 여러 줄을 입력할 경우 readline를 사용하기!

import sys input = sys.stdin.readline n = int(input()) stack = [] for _ in range(n): command = input().strip().split(' ') if command[0] == "push": stack.append(command[1]) elif command[0] == "pop": if stack: print(stack.pop()) else: print(-1) elif command[0] == "size": print(len(stack)) elif command[0] == "empty": if stack: print(0) else: print(1) elif command[0] == "top": if stack: print(stack[-1]) else: print(-1)

Copyright (c) 2023. jihyeon Choi. | All Right Reserved.