https://www.acmicpc.net/problem/10845
10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
from collections import deque
import sys
queue = deque()
order_count = int(input())
for _ in range(order_count):
order = sys.stdin.readline().strip()
if order.startswith("push"):
queue.append(order.split()[1])
elif order.startswith("pop"):
print(queue.popleft() if queue else -1)
elif order.startswith("size"):
print(len(queue))
elif order.startswith("empty"):
print(0 if queue else 1)
elif order.startswith("front"):
print(queue[0] if queue else -1)
else:
print(queue[-1] if queue else -1)
collections 모듈의 deque 객체를 사용했다.
큐를 사용하기 위한 객체이며 주요 메서드는 다음과 같다.
- append()
- appendleft()
- pop()
- popleft()
위의 메서드는 모두 시간 복잡도가 O(1) 이다.
'알고리즘 > 백준-파이썬' 카테고리의 다른 글
[백준] 10866번 (python 파이썬) (0) | 2022.04.06 |
---|---|
[백준] 1158번 (python 파이썬) (0) | 2022.04.05 |
[백준] 1406번 (python 파이썬) (0) | 2022.04.05 |
[백준] 1874번 (python 파이썬) (0) | 2022.04.04 |
[백준] 9012번 (python 파이썬) (0) | 2022.04.04 |