본문 바로가기
Algorithm/Data Structures

[파이썬] 백준 28078 : 중력 큐 (골드5)

by 베짱이28호 2025. 5. 21.

[파이썬] 백준 28078 : 중력 큐 (골드5)

[백준 28078 : 중력 큐 (골드5)](28078번: 중력 큐)


풀이

방향성 생각

  • 덱 구현하기.
  • 어느 방향인지 나타내는 state 변수를 사용.
  • 개수는 counts로 관리해주기

코드

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

state = 0
counts = [0,0]
Q = deque()
for _ in range(int(input())):
    cmd = input().split()

    if cmd[0] == 'pop' and Q:
        counts[Q.pop()] -= 1

    elif cmd[0] == 'push':
        if cmd[1] == 'b':
            Q.appendleft(0)
            counts[0] += 1
        else:
            Q.appendleft(1)
            counts[1] += 1

    elif cmd[0] == 'rotate':
        if cmd[1] == 'l':
            state = (state-1)%4
        else:
            state = (state+1)%4

    if state%2:
        while Q:
            if state==1:
                if Q[-1]==1:
                    break
                else:
                    Q.pop()
                    counts[0] -= 1
            elif state==3:
                if Q[0]==1:
                    break
                else:
                    Q.popleft()
                    counts[0] -= 1

    if cmd[0] == 'count':
        if cmd[1] == 'b':
            print(counts[0])
        else:
            print(counts[1])

코멘트

  • .

댓글