반응형

문제 링크

 

11286번: 절댓값 힙

첫째 줄에 연산의 개수 N(1≤N≤100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 0이 아니라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0

www.acmicpc.net

 

풀이 ) 우선순위큐

문제 조건에 따라 우선순위큐에 넣었다가 빼주면된다.

뺄 때 조건은 절댓값이 같을 때는 작은값 즉 음수를 꺼내고, 절댓값이 다를때는 절댓값이 작은값을 꺼내주면 된다.

 

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

public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder answer = new StringBuilder();

        int n = Integer.parseInt(br.readLine());

        PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2)->{
            if(Math.abs(o1) == Math.abs(o2)) {
                return o1-o2;
            } else {
                return Math.abs(o1)-Math.abs(o2);
            }
        });
        while(n-- > 0) {
            int x = Integer.parseInt(br.readLine());

            if(x == 0) {
                if(pq.isEmpty()) {
                    answer.append(0).append('\n');
                } else {
                    answer.append(pq.poll()).append('\n');
                }
            } else {
                pq.offer(x);
            }
        }

        System.out.println(answer.toString());
    }
}
반응형

+ Recent posts