关于堆的定义,本文不再重复板书,可另行查找。且仅做自我记录的作用。
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef int DataType;
class HeapClass {
private:
vector<DataType> data;
int size;
int capacity;
public:
HeapClass(vector<DataType>& d, int s, int c):data(d),size(s), capacity(c){}
// 两个构造函数作为初始化和创建的工具
HeapClass(int size, int capacity){
vector<DataType> DatePoint(capacity);
HeapClass(DatePoint, size, capacity);
}
void HeapPush(int value){
// 检查size == capacity ?,是否需要扩容
if(CheckFull(size)){
Expansion(capacity);
}
data[size] = value;
size++; // size将成为一个超尾标签
// 根据小根堆调整数据,采用向下调整
DownShif(0);
}
bool CheckFull(int s){ // 检查是否满
if(s == capacity){
return true; // 这里的最后一个标签的值永远为空
}
else {
return false;
}
}
void Expansion(int c){ // 扩容函数
capacity = c == 0? 5 : 2*capacity;
vector<DataType> NewData(capacity);
NewData.insert(NewData.begin(),data.begin(),data.end());
data = NewData;
}
void DownShif(int CurParent){ // 向下调整,大根堆, 0的时候将整体调整一遍
int Lchild = CurParent*2+1;
int Rchild = CurParent*2+2;
while(Lchild <= size){
if(data[Lchild] > data[CurParent]){
// 交换值来调整
SwapValue(data[Lchild], data[CurParent]);
}
if(data[Rchild] > data[CurParent]){
SwapValue(data[Rchild], data[CurParent]);
}
CurParent = Rchild + 1;
Lchild = CurParent*2+1;
Rchild = CurParent*2+2;
}
}
void SwapValue(int& a, int& b){ // 交换值的函数
int temp = a;
a = b;
b = temp;
}
bool HeapEmpty(){ // 判断堆是否为空
if(size == 0){
return true;
}else {
return false;
}
}
int HeapTop(){ // 获取堆顶的值
return data[0];
}
void HeapPop(){ // 弹出堆顶的值
SwapValue(data[0], data[size-1]);
data[size-1] = 0;
size--;
DownShif(0);
}
};
int main() {
int OpTimes = 0;
cin >> OpTimes;
HeapClass myheap(0, 5);
string oper;
int datas = 0;
while (OpTimes > 0) {
cin >> oper;
if(oper == "push"){
cin >> datas;
}
if(oper == "push"){
myheap.HeapPush(datas);
}
else if(oper == "top"){
if(!myheap.HeapEmpty()){
int outs = myheap.HeapTop();
cout<< outs <<endl;
}else {
cout << "empty"<<endl;
}
}
else if (oper == "pop") {
if(!myheap.HeapEmpty()){
int outs = myheap.HeapTop();
cout<< outs <<endl;
myheap.HeapPop();
}
else{
cout << "empty"<<endl;
}
}
OpTimes--;
}
return 0;
}