以下是小根堆定义,包括向堆中插入元素,删除堆中元素,建立新堆,调整堆等函数。
typedef int Elemtype; class MinHeap{ public: MinHeap() :elem(0), size(0){} void BuildMinHeap(vector<Elemtype> v); void Modify(int i); int Delete(); void Insert(Elemtype e); private: vector<Elemtype> elem; int size; }; void MinHeap::BuildMinHeap(vector<Elemtype> v) { elem = v; size = v.size(); int i = size / 2; while (i > 0){ Modify(i); i--; } } void MinHeap::Modify(int i) { Elemtype temp = elem[i]; int parent, child; for (parent = i; parent * 2 <= size; parent = child){ child = parent * 2; if (child + 1 <= size&&elem[child + 1] < elem[child]) child++; if (elem[child] > temp) break; else elem[parent] = elem[child]; } elem[parent] = temp; } void MinHeap::Insert(Elemtype e) { elem.push_back(e); int i; i = ++size; for (; elem[i / 2] > e; i /= 2){ elem[i] = elem[i / 2]; } elem[i] = e; } int MinHeap::Delete() { Elemtype temp = elem[1]; elem[1] = elem[size--]; elem.pop_back(); Modify(1); return temp; }
时间: 2024-11-09 03:05:41