Hyun's Wonderwall

[백준 골드2] 1655번: 가운데를 말해요 - Java 본문

Study/PS

[백준 골드2] 1655번: 가운데를 말해요 - Java

Hyun_! 2025. 10. 15. 16:21

1655번: 가운데를 말해요

https://www.acmicpc.net/problem/1655

 

문제
백준이는 동생에게 "가운데를 말해요" 게임을 가르쳐주고 있다. 백준이가 정수를 하나씩 외칠때마다 동생은 지금까지 백준이가 말한 수 중에서 중간값을 말해야 한다. 만약, 그동안 백준이가 외친 수의 개수가 짝수개라면 중간에 있는 두 수 중에서 작은 수를 말해야 한다.
예를 들어 백준이가 동생에게 1, 5, 2, 10, -99, 7, 5를 순서대로 외쳤다고 하면, 동생은 1, 1, 2, 2, 2, 2, 5를 차례대로 말해야 한다. 백준이가 외치는 수가 주어졌을 때, 동생이 말해야 하는 수를 구하는 프로그램을 작성하시오.

입력
첫째 줄에는 백준이가 외치는 정수의 개수 N이 주어진다. N은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수이다. 그 다음 N줄에 걸쳐서 백준이가 외치는 정수가 차례대로 주어진다. 정수는 -10,000보다 크거나 같고, 10,000보다 작거나 같다.

출력
한 줄에 하나씩 N줄에 걸쳐 백준이의 동생이 말해야 하는 수를 순서대로 출력한다.

예제 입력 1 
7
1
5
2
10
-99
7
5
예제 출력 1 
1
1
2
2
2
2
5


알고리즘: 자료 구조, 우선순위 큐

N의 범위가 최대 10만이다.

매번 데이터를 정렬하면 비효율적일 것이므로, 정렬된 자료구조인 힙을 이용하는 우선순위 큐 두 개를 사용해야겠다고 생각했다.

내림차순 우선순위 큐 smalls: 중앙값 이하의 값들을 저장

오름차순 우선순위 큐 bigs: 중앙값 초과의 값들을 저장 (*숫자 값이 아닌, 위치에  따른 초과를 위미)

smalls의 크기 >= bigs의 크기를 유지하며

중간의 원소를 bigs로 옮겨주는 방식으로 구현했다.

 

pq.peek()이 기억이 안 나서 첫 풀이는 다소 복잡하다.

import java.io.*;
import java.util.*;

public class Main
{
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        PriorityQueue<Integer> smalls = new PriorityQueue<>(Collections.reverseOrder());
        PriorityQueue<Integer> bigs = new PriorityQueue<>();
        for(int i=0; i<n; i++){
            int input = Integer.parseInt(br.readLine());
            if(smalls.isEmpty()){
                smalls.add(input);
            } else if (smalls.size()<=bigs.size()){
                int s=smalls.poll();
                if(s>=input) {
                    smalls.add(input);
                    smalls.add(s);
                } else {
                    int b=bigs.poll();
                    if(b>=input){
                        smalls.add(input);
                        smalls.add(s);
                        bigs.add(b);
                    } else {
                        smalls.add(s);
                        smalls.add(b);
                        bigs.add(input);
                    }
                }
            } else {
                int s=smalls.poll();
                if(s>=input) {
                    smalls.add(input);
                    bigs.add(s);
                } else {
                    smalls.add(s);
                    bigs.add(input);
                }
            }
            int sTop = smalls.poll();
            System.out.println(sTop);
            smalls.add(sTop);
        }
    }
}

 

삽입 후 균형 조정 방식으로 개선한 풀이는 다음과 같다.

import java.io.*;
import java.util.*;

public class Main
{
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        PriorityQueue<Integer> smalls = new PriorityQueue<>(Collections.reverseOrder());
        PriorityQueue<Integer> bigs = new PriorityQueue<>();
        for(int i=0; i<n; i++){
            int input = Integer.parseInt(br.readLine());
            // 삽입
            if (smalls.isEmpty() || input <= smalls.peek()) {
                smalls.offer(input);
            } else {
                bigs.offer(input);
            }
            // 균형 조정 
            if (smalls.size() > bigs.size()+1) {
                bigs.offer(smalls.poll());
            } else if (bigs.size() > smalls.size()) {
                smalls.offer(bigs.poll());
            }
            System.out.println(smalls.peek());
        }
    }
}