알고리즘(algo)/백준

[백준] 18258번 - 큐 2

dDong2 2023. 2. 19. 10:36
참고: https://www.acmicpc.net/problem/18258

 

✔️ 문제

 

 

문제는 다음과 같다.

 

 

✔️ 풀이

 

 

입력과 출력 예시는 다음과 같은데,

1과 2가 큐에 저장되면 front는 1을 back은 2를 가리키는

맨 앞과 뒤에 대해서 출력하면 된다.

나머지는 조건에 맞게 작성하면 될 것이다.

 

import sys
from collections import deque
input = sys.stdin.readline

n = int(input())
result = deque([])
for _ in range(n):
  cmd = input()
  if 'push' in cmd:
    pushs = list(cmd.split())
    result.append(pushs[1])
  if 'pop' in cmd:
    if len(result) == 0: print(-1)
    else:
      print(result[0])
      result.popleft()
  if 'size' in cmd: print(len(result))
  if 'empty' in cmd:
    if len(result) == 0: print(1)
    else: print(0)
  if 'front' in cmd:
    if len(result) == 0: print(-1)
    else: print(result[0])
  if 'back' in cmd:
    if len(result) == 0: print(-1)
    else: print(result[-1])

 

deque 라이브러리를 사용해본적이 없어서 사용해보았다.

deque에서 사용하는 append와 popleft는 시간복잡도 O(1)을

지원하기 때문에 무난하게 통과할 수 있다.

 

화이팅 💪