private int parent(int pos) {
return pos / 2;
}
private int leftChild(int pos) {
return (2 * pos);
}
private int rightChild(int pos) {
return (2 * pos) + 1;
}
private boolean isLeaf(int pos) {
return pos >= (size / 2) && pos <= size;
}
public void insert(int input) {
maxHeap[++size] = input;
int current = size;
while (maxHeap[current] > maxHeap[parent(current)]) {
swap(current, parent(current));
current = parent(current);
}
}
private void maxHeapify(int pos) {
if (isLeaf(pos)) {
return;
}
if (maxHeap[pos] < maxHeap[leftChild(pos)]
|| maxHeap[pos] < maxHeap[rightChild(pos)]) {
if (maxHeap[leftChild(pos)] > maxHeap[rightChild(pos)]) {
swap(pos, leftChild(pos));
maxHeapify(leftChild(pos));
} else {
swap(pos, rightChild(pos));
maxHeapify(rightChild(pos));
}
}
}
PriorityQueue<Integer> p = new PriorityQueue<>();
p.add(10);
p.add(30);
p.add(400);
p.add(5);
p.add(347);
System.out.println(p.peek()); // 400
최대 값이 우선순위인 큐 = 최대 힙, 최소 값이 우선순위인 큐 = 최소 힙
백준 11279 최대 힙
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int data = 0;
if (input != 0 && input < 100001) {
PriorityQueue<Integer> pq = new PriorityQueue<>(1000000, Collections.reverseOrder());
while (input != 0) {
data = sc.nextInt();
if (data != 0) {
pq.add(data);
} else {
if (pq.peek() == null) {
System.out.println(0);
} else {
System.out.println(pq.poll());
}
}
input--;
}
}
}