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


 

堆是一種經過排序的完全二叉樹,其中任一非終端節點的數據值均不大於(或不小於)其左孩子和右孩子節點的值。

 

 

 

(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]);
}

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM