堆是一種經過排序的完全二叉樹,其中任一非終端節點的數據值均不大於(或不小於)其左孩子和右孩子節點的值。
(1)根結點(亦稱為堆頂)的關鍵字是堆里所有結點關鍵字中最小者的堆稱為小根堆。
(1)根結點(亦稱為堆頂)的關鍵字是堆里所有結點關鍵字中最大者,稱為大根堆。
用堆的關鍵部分是兩個操作:
(1)put操作:即往堆中加入一個元素;
(2)get操作:即從堆中取出並刪除一個元素。【把根節點彈出】
(1)
void put(int d)
{
heap[++heap_size]=d;//大根堆
push_heap(heap+1,heap+heap_size+1);
heap1[++heap1_size]=d;//小根堆
push_heap(heap1+1,heap1+heap1_size+1,greater<int>());
}
(2)
int get()
{
pop_heap(heap+1,heap+heap_size+1,greater<int>());
return heap[heap_size--];
}
代碼如下(輸出根節點,即最大點和最小點)
#include<cstdio>
#include<functional>
#include<algorithm>
#include<iostream>
using namespace std;
int heap[101],heap_size;
int heap1[101],heap1_size;
void put(int d)
{
heap[++heap_size]=d;//大根堆
push_heap(heap+1,heap+heap_size+1);
heap1[++heap1_size]=d;//小根堆
push_heap(heap1+1,heap1+heap1_size+1,greater<int>());
}
int main()
{
int n,l,i;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&l);put(l);
}
printf("dagendui:%d\n",heap[1]);
printf("xiaogendui:%d",heap1[1]);
}