https://www.acmicpc.net/problem/10866
문제 풀이
문제 요구사항에 맞춰서 메서드를 구현하고, 조건문으로 분기처리 하면 된다! 물론 앞뒤로 빼고 요리조리 건드리는 과정에서 시간 초과가 발생할 수 있기 때문에 반드시 파이썬의 덱 컬렉션을 써서 구현해야 한다. 덱의 경우 앞뒤로 빼고 넣을 때 O(1)의 시간복잡도를 가진다.
정답 코드
import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
numbers = deque()
def push_front(x):
numbers.appendleft(x)
def push_back(x):
numbers.append(x)
def pop_front():
if not numbers:
return -1
return numbers.popleft()
def pop_back():
if not numbers:
return -1
return numbers.pop()
def size():
return len(numbers)
def empty():
if numbers:
return 0
return 1
def front():
if not numbers:
return -1
return numbers[0]
def back():
if not numbers:
return -1
return numbers[-1]
for _ in range(n):
command = list(input().split())
if command[0] == "push_front":
push_front(command[1])
elif command[0] == "push_back":
push_back(command[1])
elif command[0] == "pop_front":
print(pop_front())
elif command[0] == "pop_back":
print(pop_back())
elif command[0] == "size":
print(size())
elif command[0] == "empty":
print(empty())
elif command[0] == "front":
print(front())
elif command[0] == "back":
print(back())
'PS > 백준' 카테고리의 다른 글
[백준] 13458번 시험 감독 (python) (0) | 2024.07.07 |
---|---|
[백준] 1021번 회전하는 큐 (python) (1) | 2024.07.02 |
[백준] 2164번 카드2 (python) (0) | 2024.07.02 |
[백준] 9465번 스티커 (python) (0) | 2024.05.02 |
[백준] 3085번 사탕 게임 (python) (1) | 2024.04.06 |