二叉树基础-实现堆结构(数据结构基础 第5周)
来源:互联网 发布:优化整站 编辑:程序博客网 时间:2024/05/16 18:42
问题描述
分析
自己实现个最小堆即可
源码
#include <iostream>using namespace std;template <class T>class MinHeap {private: T* heapArray; //存放堆数据的数组 int CurrentSize; //当前堆中的元素数目 int MaxSize; //最大元素数目public: MinHeap(const int n); //构造函数,参数n为堆的最大元素数目 virtual ~MinHeap() {delete []heapArray;}; //析构函数 int parent(int pos) const; //返回父结点位置 bool RemoveMin(T& node); //从堆顶删除最小值 bool Insert(const T& newNode); //向堆中插入新元素 void SiftDown(int left); //从left开始向下筛选 void SiftUp(int position); //从position向上开始调整,使序列成为堆 };int main() { int t=0; cin >> t; while(t--) { int n=0; cin >> n; MinHeap<int> hp(n); //总共执行n次操作,堆容量置为n即可 while(n--) { int a=0; cin >> a; if (a==1) { int b=0; cin >> b; hp.Insert(b); } else if (a==2) { int b=0; hp.RemoveMin(b); cout << b << endl; } } } return 0;}template<class T>MinHeap<T>::MinHeap(const int n){ if(n<=0) return; CurrentSize=0; MaxSize=n; heapArray=new T[MaxSize]; //创建堆空间}template<class T>int MinHeap<T>::parent(int pos) const // 返回父节点位置{ return (pos-1)/2;}template<class T>void MinHeap<T>::SiftDown(int left){ int i=left; //标识父结点 int j=2*i+1; //标识关键值较小的子结点 T temp=heapArray[i]; //保存父结点 //过筛 while(j<CurrentSize) { if((j<CurrentSize-1)&&(heapArray[j]>heapArray[j+1])) j++; //j指向右子结点 if(temp>heapArray[j]) { heapArray[i]=heapArray[j]; i=j; j=2*j+1; } else break; } heapArray[i]=temp;}template<class T>void MinHeap<T>::SiftUp(int position) {//从position向上开始调整,使序列成为堆 int temppos=position; T temp=heapArray[temppos]; while((temppos>0)&&(heapArray[parent(temppos)]>temp)) { heapArray[temppos]=heapArray[parent(temppos)]; temppos=parent(temppos); } heapArray[temppos]=temp;}template<class T>bool MinHeap<T>::RemoveMin(T& node){ if(CurrentSize==0){ return false; } else{ node = heapArray[0]; heapArray[0]=heapArray[--CurrentSize]; //用最后的元素代替被删除的元素 if (CurrentSize>1) { SiftDown(0); } return true; }}template<class T>bool MinHeap<T>::Insert(const T& newNode){//向堆中插入一个结点 if(CurrentSize>=MaxSize) return false; heapArray[CurrentSize]=newNode; SiftUp(CurrentSize); CurrentSize++; return true;}
0 0
- 二叉树基础-实现堆结构(数据结构基础 第5周)
- 二叉树应用-最小堆类模板的实现(数据结构基础 第6周)
- 二叉树基础-二叉树类模板的实现(数据结构基础 第5周)
- 二叉树基础-文本二叉树(数据结构基础 第5周)
- 二叉树应用-二叉搜索树类模板的实现(数据结构基础 第6周)
- 【数据结构】第4周 二叉树基础
- 数据结构基础 之 二叉堆实现堆排序
- 数据结构基础:二叉树,堆,多叉树
- 二叉树应用-Huffman树类模板的实现(数据结构基础 第6周)
- 二叉树基础-由中根序列和后根序列重建二叉树(数据结构基础 第5周)
- 二叉树应用-二叉搜索树(数据结构基础 第6周)
- 【数据结构与算法基础】优先队列(二叉堆实现) / Priority Queue implemented by binary heap
- 数据结构基础 之 二叉堆 概念篇
- 【数据结构基础】线索二叉树(递归实现)
- 二叉树应用-Huffman编码树(数据结构基础 第6周)
- 二叉树应用-表达式·表达式树·表达式求值(数据结构基础 第6周)
- 二叉树结构--基础
- 算法学习基础篇(四):数据结构(堆、二叉搜索树、并查集)
- sort(t+1,t+n+1,cmp);三个参数分别什么意思?
- matlab 图像白平衡(世界灰度法)
- android sdk 百度网盘
- 如何扒网站
- 啦啦啦Ext.Net(一):Ext:GridPanel概述
- 二叉树基础-实现堆结构(数据结构基础 第5周)
- Android退出应用程序,完全退出!
- POJ 3320 Jessica's Reading Problem (STL)
- HTML标签总结
- C#类型基础
- 二叉树java笔试操作总结
- Sphinx学习之sphinx的安装篇(linux)
- 前景检测算法(七)--ViBe算法
- mysql数据库部分性能问题分析及优化