큐 관련 문제 풀이 boj python

청천·2022년 9월 10일
0

백준

목록 보기
17/41

이제는 bfs를 공부할 때가 온거 같아 큐를 공부해보았다.

https://www.acmicpc.net/problem/2164
카드 2

from collections import deque
N = int(input())
cards = deque(i+1 for i in range(N))

while len(cards) > 0:
    if len(cards) > 1:
        card = cards.popleft()
    else:
        print(cards[0])
        break
    if len(cards) > 1:
        card = cards.popleft()
        cards.append(card)
    else:
        print(cards[0])
        break

큐, 큐2
https://www.acmicpc.net/problem/10845
https://www.acmicpc.net/problem/18258
큐2를 먼저 풀었는 데
큐와 큐2의 차이는 N의 범위 차이였다.
같은 코드로 날먹해버렸다.

from collections import deque
N = int(input()) # 명령어 개수
queue = deque()
for _ in range(N):
    command = input()
    if command.startswith('push'):
        num = int(command.split()[1])
        queue.append(int(num))
    elif command.startswith('front'):
        if len(queue):
            print(queue[0])
        else:
            print(-1)
    elif command.startswith('back'):
        if len(queue):
            print(queue[-1])
        else:
            print(-1)
    elif command.startswith('size'):
        print(len(queue))
    elif command.startswith('empty'):
        if len(queue):
            print(0)
        else:
            print(1)
    elif command.startswith('pop'):
        if len(queue) == 0:
            print(-1)
        else:
            num = queue.popleft()
            print(num)

0개의 댓글