본문 바로가기

Baekjoon

[Baekjoon]백준 18258 큐 2(실버 4) - Python

문제설명
예제

문제를 살펴보면 큐의 역할을 수행하는 코드를 작성하면 된다

일단 n을 입력받고, n번만큼 명령을 받아 큐에 대한 실행을 하는 것을 알 수 있다

import sys를 통해 sys.stdin.readline()으로 입력을 받아주되, split()을 통해 분리하여 받아주어야 한다

push 명령어가 존재하기 때문이다

그 이후에는 cmd[0]이 어떤 명령어인지 확인하고, push라면 cmd[1]을 확인하여 값을 큐에 추가해주면 된다

파이썬에서 큐 모듈을 사용해본적이 없어서 pop 명령어에서 맨 앞의 값을 출력하고 그 이후에 슬라이싱으로 

값을 저장하도록 코드를 작성하여 제출하였다 정답률이 30퍼대이길래 조금 불안했지만 그 예감은 틀리지 않았다

import sys

n = int(input())
queue = []

for _ in range(n):
    cmd = sys.stdin.readline().split()
    if cmd[0] == 'push':
        queue.append(cmd[-1])
    elif cmd[0] == 'pop':
        if len(queue) != 0:
            print(queue[0])
            queue[:-1] = queue[1:]
            queue.pop()
        else:
            print(-1)
    elif cmd[0] == 'size':
        print(len(queue))
    elif cmd[0] == 'empty':
        if len(queue) == 0:
            print(1)
        else:
            print(0)
    elif cmd[0] == 'front':
        if len(queue) != 0:
            print(queue[0])
        else:
            print(-1)
    elif cmd[0] == 'back':
        if len(queue) != 0:
            print(queue[-1])
        else:
            print(-1)

시간초과가 발생한다 그래서 이번에는 검색하여 큐의 앞의 값을 없애주는 함수가 존재하는지 확인해보니

deque 모듈에서 popleft()가 존재함을 알 수 있었다

이를 사용하면 시간도 줄이고 편하게 구현이 가능할 것 같아서 이를 넣고 제출해보니 정답임을 확인할 수 있었다

import sys
from collections import deque

n = int(input())
queue = deque()

for _ in range(n):
    cmd = sys.stdin.readline().split()
    if cmd[0] == 'push':
        queue.append(cmd[-1])
    elif cmd[0] == 'pop':
        if len(queue) != 0:
            print(queue.popleft())
        else:
            print(-1)
    elif cmd[0] == 'size':
        print(len(queue))
    elif cmd[0] == 'empty':
        if len(queue) == 0:
            print(1)
        else:
            print(0)
    elif cmd[0] == 'front':
        if len(queue) != 0:
            print(queue[0])
        else:
            print(-1)
    elif cmd[0] == 'back':
        if len(queue) != 0:
            print(queue[-1])
        else:
            print(-1)