150. 가운데를 말해요

아현·2021년 7월 7일
0

Algorithm

목록 보기
151/400

백준




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):
        # max_heap
        heapq.heappush(maxq, (-num, num))
    else:
        # min_heap
        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() {
    //freopen("res/B1655.in", "r", stdin);
    scanf("%d", &n);
    for (int i = 0 ; i < n ; i++) {
        int a;
        scanf("%d", &a);
        // processing 
        if (min_pq.size() == max_pq.size()) {
            // to max_pq
            max_pq.push(a);
        }
        else {
            // to min_pq
            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);
        }
        //min_pq.top() < max_pq.top()   ==> 바꾼다.. 
        // print
        printf("%d\n", max_pq.top());
    }
}

profile
For the sake of someone who studies computer science

0개의 댓글