문제 링크 : https://www.acmicpc.net/problem/10845
10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
풀이
Queue의 다양한 메서드들을 구현하는 문제이다. 파이썬의 deque와 sys.stdin.readline()을 통해 시간제한 안에서 여유롭게 통과할 수 있다. 실버 4 문제라기엔 파이썬 코더에겐 상당히 쉬운 문제라고 할 수 있다.
import sys # sys.stdin.readline()을 사용해 더 빠르게 입력 받기 가능
from collections import deque # list보다 대부분의 경우에서 더 빠른 deque 사용
def push(queue, num): # 정수 num을 queue에 저장
queue.appendleft(num)
def pop(queue): # queue의 가장 앞에 위치한 정수를 뺀 후에, 그 수 반환
if len(list(queue)) == 0: # 비었다면 -1 출력
print(-1)
else:
print(queue.pop())
def size(queue): # queue에 들어있는 정수의 수 반환
print(len(queue))
def empty(queue): # queue가 비었다면 1을, 그렇지 않다면 0을 반환
if len(queue) == 0:
print(1)
else:
print(0)
def front(queue): # queue의 가장 앞에 위치한 수 반환
if len(queue) == 0:
print(-1)
else:
print(queue[len(queue)-1])
def back(queue): # queue의 가장 뒤에 위치한 수 반환
if len(queue) == 0:
print(-1)
else:
print(queue[0])
queue = deque()
for _ in range(int(sys.stdin.readline())):
cmd = list(sys.stdin.readline().split()) # cmd[0]은 명령어, cmd[1]은 push 될 값
if cmd[0] == 'push':
push(queue, cmd[1])
if cmd[0] == 'pop':
pop(queue)
if cmd[0] == 'size':
size(queue)
if cmd[0] == 'empty':
empty(queue)
if cmd[0] == 'front':
front(queue)
if cmd[0] == 'back':
back(queue)
'알고리즘 > 알고리즘 문제 풀이' 카테고리의 다른 글
(Python) 백준 1874번 - 스택 수열 (0) | 2023.01.10 |
---|---|
(Python) 백준 10866번 - 덱 (0) | 2023.01.10 |
(Python) 백준 10828번 - 스택 (0) | 2023.01.10 |
(Python) 백준 10816번 - 숫자 카드 2 (0) | 2023.01.10 |
(Python) 백준 10773번 - 제로 (0) | 2023.01.09 |