Skip to content

Commit 1cb546f

Browse files
committed
[BOJ] 1655 가운데를 말해요 (G2)
1 parent 3c129f1 commit 1cb546f

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

심수연/4주차/260120.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# https://www.acmicpc.net/problem/1655
2+
3+
import sys
4+
import heapq
5+
6+
input = sys.stdin.readline
7+
8+
left = [] # max heap
9+
right = [] # min heap
10+
11+
N = int(input())
12+
13+
for _ in range(N):
14+
x = int(input())
15+
16+
# left에 우선 넣기
17+
heapq.heappush(left, -x) # max heap에는 - 로 넣기
18+
19+
# left의 최대 <= right의 최소가 되도록 만들기
20+
if right and (-left[0] > right[0]): # left의 최대가 right의 최소보다 크다면
21+
# swap
22+
a = -heapq.heappop(left) # left의 최대
23+
b = heapq.heappop(right) # right의 최소
24+
heapq.heappush(left, -b)
25+
heapq.heappush(right, a)
26+
27+
# left가 right보다 같거나 1개 많도록 만들기
28+
if len(left) > len(right) + 1: # left가 right 개수 + 1 보다 더 많다면
29+
# left에서 right로 넘기기
30+
a = -heapq.heappop(left)
31+
heapq.heappush(right, a)
32+
elif len(left) < len(right): # right가 left 개수보다 더 많다면
33+
# right에서 left로 넘기기
34+
b = heapq.heappop(right)
35+
heapq.heappush(left, -b)
36+
37+
print(-left[0])

0 commit comments

Comments
 (0)