資源簡介
c++ 最小堆 還不錯(cuò) 標(biāo)準(zhǔn)庫沒有 自己做作業(yè)用。
代碼片段和文件信息
template???
class?MinHeap?{???
public:???
????MinHeap(int?MinHeapSize?=?10);???
????~MinHeap()?{delete?[]?heap;}???
????int?Size()?const?{return?CurrentSize;}???
????T?Min()?{if?(CurrentSize?==?0)???
??????????????throw?OutOfBounds();???
???????????return?heap[1];}???
????MinHeap&?Insert(const?T&?x);???
????MinHeap&?DeleteMin(T&?x);???
????void?Initialize(T?a[]?int?size?int?ArraySize);???
????void?Deactivate()?{heap?=?0;}???
????void?Output()?const;???
private:???
????int?CurrentSize?MaxSize;???
????T?*heap;???
};???
??
template???
MinHeap::MinHeap(int?MinHeapSize)???
{???
????MaxSize?=?MinHeapSize;???
????heap?=?new?T[MaxSize+1];???
????CurrentSize?=?0;???
}???
??
template???
MinHeap&?MinHeap::Insert(const?T&?x)???
{???
????if?(CurrentSize?==?MaxSize)???
????????throw?NoMem();???
??
????//為x尋找應(yīng)插入的位置???
????//i從新的葉節(jié)點(diǎn)開始,并沿著樹上升???
????int?i?=?++CurrentSize;???
????while?(i?!=?1?&&?x?????{???
????????heap[i]?=?heap[i/2];?//?將元素下移???
????????i?/=?2;??????????????//?移向父節(jié)點(diǎn)???
????}???
????heap[i]?=?x;???
??
????return?*this;???
}???
??
template???
MinHeap&?MinHeap::DeleteMin(T&?x)???
{???
????if?(CurrentSize?==?0)???
????????throw?OutOfBounds();???
??
????x?=?heap[1];???
??
????T?y?=?heap[CurrentSize--];?//最后一個(gè)元素???
??
????//?從根開始?為y尋找合適的位置???
????int?i?=?1??//?堆的當(dāng)前節(jié)點(diǎn)???
???????ci?=?2;??//?i的子節(jié)點(diǎn)???
??
????while?(ci?<=?CurrentSize)????
評論
共有 條評論