알고리즘 공부(백준)
[11286] 절댓값 힙
Leezu_
2021. 1. 2. 18:14
입력받은 값과 그 값의 절댓값을 묶어서 PriorityQueue에 넣어 푼 문제
(compareTo를 오버라이드하여 정렬)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.PriorityQueue;
//절댓값과 기존값을 묶은 pair 클래스
class pair implements Comparable<pair> {
int ab, a;
public pair(int ab, int a) {
this.ab = ab;
this.a = a;
}
//절댓값을 기준으로 정렬하되, 같으면 기존값을 기준으로 정렬
@Override
public int compareTo(pair o) {
if (this.ab > o.ab) {
return 1;
} else if (this.ab == o.ab) {
if (this.a > o.a) {
return 1;
} else {
return -1;
}
} else {
return -1;
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
PriorityQueue<pair> q = new PriorityQueue<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
for(int i=0; i<n; i++) {
int a = Integer.parseInt(br.readLine());
if(a == 0) {
if(q.isEmpty()) {
bw.write("0\n");
} else {
bw.write(Integer.toString(q.poll().a) + "\n");
}
} else {
int ab = Math.abs(a);
q.add(new pair(ab, a));
}
}
bw.flush();
bw.close();
}
}