用大根堆实现大值优先队列
来源:互联网 发布:程序员 出差吗 编辑:程序博客网 时间:2024/05/16 09:06
今天学了数据结构中的堆,堆分为大根堆和小根堆。大根堆是什么呢?大根堆是指一颗即
是完全二叉树又是大根树的树。那什么是大根树,和完全二叉树呢?去百度google一下就知道了。
小根堆是一个与大根堆类似的概念,联想一下吧。
大根堆和小根堆有何用呢?用处当然是有的,有人说可以用来实现大值优先队列和小值优
先队列。所以下面就大根堆来实现一个大值优先队列heap。这个队列提供两个操作函数,一个是
push,一个是pop。push是把一个节点入列,pop是把节点出列,也就是删除一个节点。
下面是代码实现
#include <stdlib.h>#include <stdio.h>#define MAX_ELEMENTS 200#define HEAP_FULL(n) (n == MAX_ELEMENTS - 1)#define HEAP_EMPTY(n) (!n)typedef struct{int key;char c;/* add other fields */} element;element heap[MAX_ELEMENTS];void push(element item, int *n){int i = 0;if(HEAP_FULL(*n)){fprintf(stderr, "The heap is full.\n");exit(0);}i = ++(*n);while(i != 1 && item.key > heap[i / 2].key){heap[i] = heap[i / 2];i /= 2;}heap[i] = item;}// delete element with the highest key from the heapelement pop(int *n){int parent = 0, child = 0;element item, temp;if(HEAP_EMPTY(*n)){fprintf(stderr, "the heap is empty.\n");exit(0);}// save value of the element with the highest keyitem = heap[1];// use last element in heap to adjust heap parenttemp = heap[(*n)--];parent = 1;child = 2;while(child <= *n){// find the larger child of the current parentif(child < *n && heap[child].key < heap[child + 1].key)child++;if(temp.key >= heap[child].key)break;// move to the next lower levelheap[parent] = heap[child];parent = child;child *= 2;}heap[parent] = temp;return item;}int main(){int n = 0; // node countsint num[] = {2, 5, 18, 7, 9, 4, 3};element item;// push all node into queuefor(int i = 0; i < sizeof(num) / sizeof(int); i++){item.key = num[i];item.c = 'a';push(item, &n);}// pop all node out of queuewhile(n > 0){item = pop(&n);printf("item.key = %d, ch = %c\n", item.key, item.c);}getchar();return 0;}大家可以把代码拷贝调试看看,会发现在内存heap中不是按key值从大到小排列的,但pop打印的数值是从大到小,很神奇吧。
- 用大根堆实现大值优先队列
- 优先队列实现哈弗曼最小权值
- Python实现优先队列
- 优先队列实现堆
- 优先队列的实现
- 优先队列实现栈
- Python实现优先队列
- 优先队列实现
- 优先队列(堆实现)
- 实现一个优先队列
- 优先队列 C实现
- C++实现优先队列
- 优先队列初级实现
- 优先队列的实现
- 用 C# 实现优先队列
- 用 C# 实现优先队列
- Huffman编码优先队列实现
- 用堆实现优先队列
- 以Groovy的方式更稳定地解析HTML
- netlink
- CSDN资源积分怎么获得?
- 排列的分解
- 用C#编写网络电话
- 用大根堆实现大值优先队列
- Java第一个程序的第一个错误
- 解析String类型的XML
- OD隐藏
- 使用Ant部署项目的15个步骤
- Java中字符串split方法使用简介
- C#实现虚拟桌面
- Audacious实现cue、ape音乐支持,GBK支持、cue乱码完美解决
- 浪潮php实习第二天(php开源框架zend Framework初探)