-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathheap.h
More file actions
74 lines (63 loc) · 1.29 KB
/
heap.h
File metadata and controls
74 lines (63 loc) · 1.29 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
#include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
#include<functional>
using namespace std;
class Heap
{
typedef function<bool(int, int)> compare;
private:
vector<int> _vec;
int heapsize;
compare comp;
public:
//default minheap
Heap(compare c = less<int>()): heapsize(0), comp(c) {}
~Heap() = default;
//c++11 construct with list
//such as Heap{4,3,2,1}
Heap(initializer_list<int> list, compare c = less<int>()): _vec(list.begin(), list.end()), heapsize(list.size()), comp(c)
{
for (int i = heapsize / 2 - 1; i >= 0; --i)
siftdown(i, comp);
}
//construct with vector
Heap(vector<int> vec, compare c = less<int>()): _vec(vec.begin(), vec.end()), heapsize(vec.size()), comp(c)
{
for (int i = heapsize / 2 - 1; i >= 0; --i)
siftdown(i, comp);
}
void siftdown(int pos, compare comp);
void insert(int value);
int remove(int pos);
int removeroot();
int size() const
{
return heapsize;
}
bool isLeaf(int pos) const
{
return pos >= heapsize / 2 && pos < heapsize;
}
int parent(int pos) const
{
return (pos - 1) / 2;
}
int leftchild(int pos) const
{
return pos * 2 + 1;
}
int rightchild(int pos) const
{
return pos * 2 + 2;
}
void printHeap()
{
for (int i = 0; i < heapsize; i++)
{
cout << _vec[i] << " ";
}
cout << endl;
}
};