public class PriorityQueue
{
// 最小堆
public PriorityQueue(int max)
{
this.heap = new int[max + 2];
this.max = max + 1;
}
// 维护的堆数据
private int[] heap;
// 优先队列的最大容量
private int max;
// 队列指针
private int capacity = 0;
// 插入数据
public void insert(int key)
{
this.heap[++this.capacity] = key;
swim(capacity);
if (capacity == this.max)
{
this.deleteMin();
}
}
// 删除最小值
public int deleteMin()
{
int min = this.heap[1];
this.heap[1] = this.heap[capacity];
this.heap[capacity--] = 0;
sink(1);
return min;
}
// 上浮
private void swim(int k)
{
while (k > 1)
{
if (less(this.heap[k], this.heap[k / 2]))
{
swap(k, k / 2, this.heap);
}
k /= 2;
}
}
// 下沉
private void sink(int k)
{
while (2 * k < this.capacity)
{
int j = 2 * k;
if (j < this.capacity && less(this.heap[j+1], this.heap[j]))
{
j++;
}
swap(k, j, this.heap);
k = j;
}
}
}