백준
1. python
정상 작동
import heapq
import sys
maxq, minq = [], []
n = int(sys.stdin.readline())
for _ in range(n):
num = int(sys.stdin.readline())
if len(maxq) == len(minq):
heapq.heappush(maxq, (-num, num))
else:
heapq.heappush(minq, (num, num))
if minq and maxq[0][1] > minq[0][1]:
max_value = heapq.heappop(maxq)[1]
min_value = heapq.heappop(minq)[1]
heapq.heappush(minq, (max_value, max_value))
heapq.heappush(maxq, (-min_value, min_value))
print(maxq[0][1])
런타임 에러
import sys
import heapq
input = sys.stdin.readline
n = int(input())
max_q = []
min_q = []
for _ in range(n):
a = int(input())
if len(max_q) == len(min_q):
heapq.heappush(max_q, -a)
else:
heapq.heappush(min_q, a)
if min_q and max_q and abs(min_q[0]) < abs(max_q[0]):
min_value = heapq.pop(min_q)
max_value = - heapq.pop(max_q)
heapq.heappush(max_q, -min_value)
heapq.heappush(min_q, max_value)
print(-max_q[0])
2. C++
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
priority_queue<int> max_pq;
priority_queue<int, vector<int>, greater<int>> min_pq;
int n;
int main() {
scanf("%d", &n);
for (int i = 0 ; i < n ; i++) {
int a;
scanf("%d", &a);
if (min_pq.size() == max_pq.size()) {
max_pq.push(a);
}
else {
min_pq.push(a);
}
if (!min_pq.empty() && !max_pq.empty() && min_pq.top() < max_pq.top()) {
int min_value = min_pq.top();
min_pq.pop();
int max_value = max_pq.top();
max_pq.pop();
max_pq.push(min_value);
min_pq.push(max_value);
}
printf("%d\n", max_pq.top());
}
}