Java
[백준 11286] 절댓값 힙 (JAVA)
iheeeee6-6
2023. 2. 21. 14:50
728x90
https://www.acmicpc.net/problem/11286
11286번: 절댓값 힙
첫째 줄에 연산의 개수 N(1≤N≤100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 0이 아니라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0
www.acmicpc.net
우선순위 큐를 사용하여 해결할 수 있었다.
음수일 경우에는 q2에 넣었으며 q2는 내림차순 정렬된 큐이다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
PriorityQueue<Integer> q = new PriorityQueue<>();
PriorityQueue<Integer> q2 = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < n; i++) {
int num = Integer.parseInt(br.readLine());
if (num == 0) {
if (q.isEmpty()) {
System.out.println(0);
continue;
}
if (!q2.isEmpty()) {
if (q.peek() == Math.abs(q2.peek())) {
q.poll();
System.out.println(q2.poll());
} else
System.out.println(q.poll());
} else
System.out.println(q.poll());
} else {
q.add(Math.abs(num));
if (num < 0)
q2.add(num);
}
}
}
}