#1105 : 题外话·堆
描述
小Ho有一个糖果盒子,每过一段时间小Ho都会将新买来的糖果放进去,同时他也会不断的从其中挑选出最大的糖果出来吃掉,但是寻找最大的糖果不是一件非常简单的事情,所以小Ho希望能够用计算机来他帮忙计算这个问题!
最大堆问题。代码如下:
#include <stdio.h> #include <stdlib.h> #include <vector> #include <iostream> using namespace std; template <typename Comparable> class BinaryHeap{ public: BinaryHeap(int capacity = 100){ currentSize = 0; array.resize(capacity); } void insert(const Comparable &x){ if (currentSize == array.size()) array.resize(array.size() * 2); int hole = ++currentSize; for (; hole > 1; hole = hole / 2){ if (array[hole/2] > x) break; array[hole] = array[hole / 2]; } array[hole] = x; } bool isEmpty(){ return currentSize<1; } Comparable findMax(){ if (isEmpty()){ return NULL; } return array[1]; } Comparable deleteMax(){ if (isEmpty()){ return NULL; } Comparable x = array[1]; array[1] = array[currentSize--]; Comparable temp = array[1]; int hole =1; while (2*hole <= currentSize){ int child = 2 * hole; if (child != currentSize&&array[child + 1] >array[child]){ child++; } if (array[child] > temp){ array[hole] = array[child]; } else{ break; } hole = child; } array[hole] = temp; return x; } private: int currentSize; vector<Comparable> array; }; int main(){ int N; char ch; int step = 0; int x; cin >> N; BinaryHeap<int> binaryHeap; while (step < N){ step++; cin >> ch; if (ch == 'A'){ cin >> x; binaryHeap.insert(x); } else{ x = binaryHeap.deleteMax(); cout <<x<<endl; } } return 0; }