#include<iostream>
using namespace std;
const int SIZE = 110;
int heap[SIZE], n; //heap 从下标1开始存储的,n是数组中已有的元素
void up(int p)
{
while (p > 1) {
if (heap[p] > heap[p / 2]) {
swap(heap[p], heap[p / 2]);
p = p / 2;
}
else
{
break;
}
}
}
//插入元素
void insert(int val) {
heap[++n] = val;
up(n);
}
//取最大元素
int GetTop()
{
return heap[1];
}
void down(int p)
{
int s = p * 2;
while (s <= n)
{
if (s < n && heap[s] < heap[s + 1]) s++;
if (heap[s] > heap[p]) {
swap(heap[s], heap[p]);
p = s, s = p * 2;
}
else break;
}
}
//取堆顶并弹出
int Extract()
{
int temp = heap[1];
heap[1] = heap[--n];
down(1);
return temp;
}
//删除元素
void Remove(int k)
{
heap[k] = heap[n--];
up(k), down(k); //调整元素,满足最大堆的性质
}```
<模板>大根堆
最新推荐文章于 2025-05-01 13:25:47 发布