문제링크: www.acmicpc.net/problem/11286
11286번: 절댓값 힙
첫째 줄에 연산의 개수 N(1≤N≤100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 0이 아니라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0
www.acmicpc.net
큐 두 개를 활용해서 해결했다. 코드가 긴 것 같아서 다른 사람의 풀이를 보니
우선순위 큐 하나로 담길 정보에 절대값, 원본값 두개를 같이 담아서 절대값으로 비교하고 원본값을 출력하는
방법을 사용하더라 그게 더 깔끔할 것 같다
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int loop = Integer.parseInt(br.readLine());
PriorityQueue<Integer> minus_q = new PriorityQueue<Integer>();
PriorityQueue<Integer> plus_q = new PriorityQueue<Integer>();
for(int i=0;i<loop;i++) {
int num = Integer.parseInt(br.readLine());
if(num==0) {
if(minus_q.isEmpty() && plus_q.isEmpty()) {
System.out.println(0);
continue;
}else if(minus_q.isEmpty() && !plus_q.isEmpty()) {
System.out.println(plus_q.poll());
continue;
}else if(!minus_q.isEmpty() && plus_q.isEmpty()) {
System.out.println(-minus_q.poll());
continue;
}
if(Math.abs(minus_q.peek())<=plus_q.peek()) {
System.out.println(-minus_q.poll());
}else {
System.out.println(plus_q.poll());
}
}else {
if(num>0) {
plus_q.offer(num);
}else {
minus_q.offer(-num);
}
}
}
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 1956 운동 (0) | 2020.12.23 |
---|---|
[백준] 1504 특정한 최단 경로 (0) | 2020.12.23 |
[백준] 1927 최소 힙 (0) | 2020.12.23 |
[백준] 11279 최대 힙 (0) | 2020.12.23 |
[백준] 2749 피보나치 수 3 (0) | 2020.12.20 |