-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.cpp
126 lines (105 loc) · 2.16 KB
/
heap.cpp
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <iostream>
#include <vector>
#include <unordered_map>
template<typename T>
class Heap
{
std::vector<T> data;
std::unordered_map<T, int> map;
public:
void add(T item)
{
data.push_back(item);
map[item] = data.size() - 1;
upheapify(data.size() - 1);
}
void display()
{
for (const T& item : data)
{
std::cout << item << " ";
}
std::cout << std::endl;
}
int size() const
{
return data.size();
}
bool isEmpty() const
{
return data.empty();
}
T remove()
{
swap(0, data.size() - 1);
T removedValue = data.back();
data.pop_back();
downheapify(0);
map.erase(removedValue);
return removedValue;
}
T get() const
{
return data[0];
}
void updatePriority(T item)
{
int index = map[item];
upheapify(index);
}
private:
void upheapify(int ci)
{
int pi = (ci - 1) / 2;
if (isLarger(data[ci], data[pi]) > 0)
{
swap(pi, ci);
upheapify(pi);
}
}
void downheapify(int pi)
{
int lci = 2 * pi + 1;
int rci = 2 * pi + 2;
int mini = pi;
if (lci < data.size() && isLarger(data[lci], data[mini]) > 0)
{
mini = lci;
}
if (rci < data.size() && isLarger(data[rci], data[mini]) > 0)
{
mini = rci;
}
if (mini != pi)
{
swap(mini, pi);
downheapify(mini);
}
}
void swap(int i, int j)
{
T ith = data[i];
T jth = data[j];
data[i] = jth;
data[j] = ith;
map[ith] = j;
map[jth] = i;
}
int isLarger(const T& t, const T& o) const
{
return t > o ? 1 : (t < o ? -1 : 0);
}
};
// Example usage
int main()
{
Heap<int> heap;
heap.add(10);
heap.add(20);
heap.add(5);
heap.add(15);
heap.display(); // Output: 20 15 5 10
std::cout << "Removed: " << heap.remove() << std::endl; // Output: 20
heap.display(); // Output: 15 10 5
return 0;
}