이번엔 Heap..
※ 해당 코드 사용하려면 내 블로그의 C++ Vector.h가 필요하다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | #ifndef __HEAP_H__ #define __HEAP_H__ #include "Vector.h" template <class T> struct Less{ bool operator()(const T& lhs, const T& rhs) const { return lhs<rhs; } }; template <class T> struct Greater{ bool operator()(const T& lhs, const T& rhs) const { return rhs<lhs; } }; template <class T, class Container = Vector<T>, class Cmp = Less<T>> class Heap{ private: int sz; Container arr; Cmp cmp; //Constructor & Destructor public: Heap(); virtual ~Heap() = default; //privaet functions private: void swap(T& x, T& y); void up(int at); void down(int at); //public functions public: void push(T x); void pop(); T top(); bool empty(); int size(); void print(); }; //Constructor template <class T, class Container, class Cmp> Heap<T,Container,Cmp>::Heap():sz(0) { arr.clear(); arr.resize(1); } //public functions template <class T, class Container, class Cmp> void Heap<T,Container,Cmp>::push(T x) { arr.push_back(x); sz++; up(sz); } template <class T, class Container, class Cmp> void Heap<T,Container,Cmp>::pop() { if(sz<=0) return; arr[1] = arr[sz]; arr.pop_back(); sz--; down(1); } template <class T, class Container, class Cmp> T Heap<T,Container,Cmp>::top() { if(sz<=0) exit(1); //error return arr[1]; } template <class T, class Container, class Cmp> bool Heap<T,Container,Cmp>::empty() { return sz<=0; } template <class T, class Container, class Cmp> int Heap<T,Container,Cmp>::size() { return sz; } template <class T, class Container, class Cmp> void Heap<T,Container,Cmp>::print() { for(int i=1; i<=sz; i++) { arr[i].print(); printf(" "); } } //private functions template <class T, class Container, class Cmp> void Heap<T,Container,Cmp>::swap(T& x, T& y) { T tmp=x; x=y; y=tmp; } template <class T, class Container, class Cmp> void Heap<T,Container,Cmp>::up(int at) { if(at<=1) return; int par = at/2; if(cmp(arr[par],arr[at])) { swap(arr[par],arr[at]); up(par); } } template <class T, class Container, class Cmp> void Heap<T,Container,Cmp>::down(int at) { int l=at*2, r=at*2+1, pos=at; if(l<=sz) if(cmp(arr[pos],arr[l])) pos=l; if(r<=sz) if(cmp(arr[pos],arr[r])) pos=r; if(pos!=at) { swap(arr[at], arr[pos]); down(pos); } } #endif | cs |
'Algorithm > Data Structure' 카테고리의 다른 글
[Ex준비] Vector, MaxHeap, MinHeap → .cpp로 구현 (0) | 2018.11.09 |
---|---|
[Ex준비] C++ Vector.h (4) | 2018.11.09 |
구간 업데이트와 구간 합이 모두 O(logN)에 가능한 펜윅트리 (Fenwick Tree Lazy Propagation) (4) | 2018.08.04 |