Repository navigation
Expand file tree
/
Copy pathHeap.hpp
More file actions
79 lines (63 loc) · 1.71 KB
/
Copy pathHeap.hpp
File metadata and controls
79 lines (63 loc) · 1.71 KB
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
#pragma once
#include <vector>
using namespace std;
template <typename T>
class MaxHeap{
private:
vector<T> arr;
int parent(int i){
return ((i-1)/2);
}
int leftchild(int i){
return(2*i+1);
}
int rightchild(int i){
return (2*i+2);
}
void heapifyUp(int i)
{
while(i>0 and arr[parent(i)] < arr[i])
{
swap(arr[i],arr[parent(i)]);
i=parent(i);
}
}
void heapifyDown(int i){
int root=i;
int left= leftchild(i);
int right=rightchild(i);
if(left<arr.size() and arr[left]>arr[root])
root=left;
if(right<arr.size() and arr[right]>arr[root])
root=right;
if(root!=i)
{
swap(arr[i],arr[root]);
heapifyDown(root);
}
}
public:
void push(T v){
arr.push_back(v);
heapifyUp(arr.size()-1);
}
void pop(){
if(arr.empty())
return;
arr[0]=arr.back();
arr.pop_back();
if(!arr.empty())
heapifyDown(0);
}
T top(){
if(arr.empty())
throw runtime_error("Heap is empty");
return arr[0];
}
bool empty(){
return(arr.empty());
}
int size(){
return arr.size();
}
};