From 0c862db2059f983bf7e7eab937176390e9602eee Mon Sep 17 00:00:00 2001 From: TUNQRT Date: Tue, 18 Feb 2025 13:53:54 +0100 Subject: [PATCH] pop&push --- heap.cpp | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 heap.cpp diff --git a/heap.cpp b/heap.cpp new file mode 100644 index 0000000..e04574c --- /dev/null +++ b/heap.cpp @@ -0,0 +1,93 @@ +#include +#include +#include +#include + + +class Heap { +public: + int pop(); + void push(int); + void print() const; + bool empty() const; +private: + std::vector data; + + void dump(std::ofstream&, int) const; +}; + +void Heap::push(int h){ + data.push_back(h); + for(int i = data.size(); i > 1; i /= 2){ + if(data.at(i-1) < data.at(i/2-1)) std::swap(data[i-1], data[(i/2)-1]); + else break; + } +} + +int Heap::pop(){ + if (empty()) throw std::out_of_range("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + std::swap(data[0], data[data.size()-1]); + int garbage = data.back(); + data.pop_back(); + + int muj_index = 0; + while(true){ + if(data.size() <= 2*muj_index+1) break; + int small_child_i; + if(data.size() > 2*muj_index+2 && data.at(2*muj_index+2) < data.at(2*muj_index+1)) + small_child_i = 2*muj_index+2; + else small_child_i = 2*muj_index+1; + + if(data.at(muj_index) > data.at(small_child_i)){ + std::swap(data[muj_index], data[small_child_i]); + muj_index = small_child_i; + }else break; + } + + return garbage; +} + +bool Heap::empty() const{ + return data.empty(); +} + + +void Heap::dump(std::ofstream& ofs, int idx) const { + if (data.size() - 1 > 2 * idx) { + ofs << data[idx] << " -> " << data[idx * 2 + 1] << '\n'; + dump(ofs, idx * 2 + 1); + } + if (data.size() - 1 > 2 * idx + 1) { + ofs << data[idx] << " -> " << data[idx * 2 + 1 + 1] << '\n'; + dump(ofs, idx * 2 + 1 + 1); + } +} + +void Heap::print() const { + std::ofstream ofs; + ofs.open("viz.dot"); + ofs << "digraph Tree {\n"; + dump(ofs, 0); + ofs << "}"; + + ofs.close(); + system("cat viz.dot | dot -Tx11"); +} + + + +int main() { + Heap h; + std::vector v = {1, 4, 9, 0, 7, 5, 8}; + + for (auto i : v) { + h.push(i); + h.print(); + } + + while (!h.empty()){ + int i = h.pop(); + h.print(); + } + int aaaaaaaaaaaaaaa = h.pop(); +} \ No newline at end of file