This commit is contained in:
TUNQRT 2025-02-18 13:53:54 +01:00
commit 0c862db205
1 changed files with 93 additions and 0 deletions

93
heap.cpp Normal file
View File

@ -0,0 +1,93 @@
#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
class Heap {
public:
int pop();
void push(int);
void print() const;
bool empty() const;
private:
std::vector<int> 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<int> 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();
}