문제 : https://www.acmicpc.net/problem/28278
풀이
이 문제는 스택과 관련된 문제이다. 스택을 구현하면서 특정 명령을 처리하는 것이다.
예전에 자료구조를 했던 기억이 있어서 거기서 따로 함수별로 나눠서 명령을 처리하던 것이 기억나 그대로 수행하였다.
import sys
input = sys.stdin.readline
n = int(input().strip())
stack = []
def push(x):
stack.append(x)
def pop():
if stack:
print(stack.pop())
else:
print(-1)
def size():
print(len(stack))
def empty():
if stack:
print(0)
else:
print(1)
def top():
if stack:
print(stack[-1])
else:
print(-1)
# 명령어와 함수 매핑
commands = {
1: push,
2: pop,
3: size,
4: empty,
5: top
}
for _ in range(n):
cmd = list(map(int, input().strip().split()))
# cmd[0]을 함수로 호출
if cmd[0] == 1:
commands[cmd[0]](cmd[1]) # 'push'는 cmd[1]도 필요
else:
commands[cmd[0]]() # 나머지 명령어들은 인자 필요 없음
결과
'Algorithm > 알고리즘' 카테고리의 다른 글
[백준/자바] 1260번 - DFS와 BFS 구현하기 (1) | 2025.01.17 |
---|---|
[백준/자바] 1157 - 단어 공부 (1) | 2025.01.16 |
함수와 재귀함수(Python) (0) | 2024.05.20 |
알고리즘에 도움되는 간단한 파이썬 문법 (0) | 2024.05.12 |
복잡도 (0) | 2024.04.22 |