https://www.acmicpc.net/problem/10828
스택은 자료구조 중 한 유형으로, 먼저 들어간 원소는 가장 나오는 출입구가 단방향인 자료구조이다.
그 특성 상 사용처가 유의미 한 경우가 있어 자주 사용한다.
몇 년전 나는 이 문제를 풀었는데, 그냥 STL에 있는거에 매핑한 수준 밖에 안되더라.
완전히 새로하느라 시간이 조금 필요했다.
import sys
def empty(idx):
if myStack[idx] is None:
return True
else:
return False
def top(idx):
if not empty(idx):
return myStack[idx]
else:
return -1
def size(idx):
return idx + 1
def pop(idx):
if not empty(idx):
output = myStack[idx]
myStack[idx] = None
return output
else:
return -1
def push(item, idx):
myStack[idx] = item
return
commandList = int(sys.stdin.readline())
myStack = [None] * 10000
curStackIdx = -1
for i in range(commandList):
command = sys.stdin.readline().strip()
if " " in command:
# 여긴 Push N 전용
parts = command.split(" ")
curStackIdx += 1
push(parts[1], curStackIdx)
else:
if command == "top":
print(top(curStackIdx))
elif command == "size":
print(size(curStackIdx))
elif command == "empty":
if empty(curStackIdx) :
print("1")
else:
print("0")
elif command == "pop":
popResult = pop(curStackIdx)
if popResult != -1:
curStackIdx -= 1
print(popResult)
'문제풀이' 카테고리의 다른 글
[PY] 9012 : 괄호 (0) | 2025.03.24 |
---|---|
[PY] 10773 : 제로 (0) | 2025.03.24 |
[PY] 2110 : 공유기 설치 (0) | 2025.03.24 |
[PY] 11503 : 가장 긴 증가하는 부분 수열 (0) | 2025.03.23 |
[PY] 1629 : 곱셈 (0) | 2025.03.22 |