✔ 풀이를 위한 아이디어
✔ 수정 전 코드
import sys
import heapq
T = int(sys.stdin.readline())
for _ in range(T):
max_Heap = []
min_Heap = []
count = 0
k = int(sys.stdin.readline())
for _ in range(k):
cmd, num = sys.stdin.readline().strip().split()
if cmd == 'I':
heapq.heappush(max_Heap, (-int(num), int(num)))
heapq.heappush(min_Heap, int(num))
count += 1
elif cmd == 'D' and count > 0:
if int(num) == 1:
heapq.heappop(max_Heap)
else:
heapq.heappop(min_Heap)
count -= 1
if count > 0:
print(heapq.heappop(max_Heap)[1], heapq.heappop(min_Heap))
else:
print("EMPTY")
✔ 수정 후 코드
import sys
import heapq
T = int(sys.stdin.readline())
for _ in range(T):
max_Heap = []
min_Heap = []
k = int(sys.stdin.readline())
visited = [False]*k
for i in range(k):
cmd, num = sys.stdin.readline().strip().split()
if cmd == 'I':
heapq.heappush(max_Heap, (-int(num), i))
heapq.heappush(min_Heap, (int(num), i))
visited[i] = True
elif cmd == 'D':
if int(num) == 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)
if max_Heap and min_Heap:
print(-max_Heap[0][0], min_Heap[0][0])
else:
print("EMPTY")
✔ 관련 개념
개고수 ㄷㄷㄷㄷ