컴공생의 다이어리

[파이썬, Python] 백준 7662번 : 이중 우선순위 큐 본문

Development/Algorithm & Coding Test

[파이썬, Python] 백준 7662번 : 이중 우선순위 큐

컴공 K 2022. 5. 16. 00:01

백준 7662번 : 이중 우선순위 큐

(문제 바로가기)

 

 

 

내 코드

import sys, heapq
from collections import defaultdict

input = sys.stdin.readline

for _ in range(int(input())):
    max_heap, min_heap = list(), list()
    visited = defaultdict(bool)

    for j in range(int(input())):
        command = list(input().split())
        if command[0] == 'I':   # 데이터 삽입
            heapq.heappush(min_heap, (int(command[1]), j))
            heapq.heappush(max_heap, (-int(command[1]), j))
            visited[j] = True
        else:   # 삭제
            if command[1] == '1':  # 최댓값 삭제
                while max_heap and not visited[max_heap[0][1]]:
                    heapq.heappop(max_heap)
                if max_heap:
                    visited[max_heap[0][1]] = False
                    heapq.heappop(max_heap)
            else:   # 최솟값 삭제
                while min_heap and not visited[min_heap[0][1]]:
                    heapq.heappop(min_heap)
                if min_heap:
                    visited[min_heap[0][1]] = False
                    heapq.heappop(min_heap)

    while max_heap and not visited[max_heap[0][1]]: heapq.heappop(max_heap)
    while min_heap and not visited[min_heap[0][1]]: heapq.heappop(min_heap)

    print(-max_heap[0][0], min_heap[0][0]) if max_heap and min_heap else print("EMPTY")

 

 

728x90
Comments