【堆】 大根堆和小根堆的建立

堆是一种经过排序的完全二叉树,其中任一非终端节点的数据值均不大于(或不小于)其左孩子和右孩子节点的值。

(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
",heap[1]);
	printf("xiaogendui:%d",heap1[1]);
}
原文地址:https://www.cnblogs.com/Orz-IE/p/12039538.html