-
Notifications
You must be signed in to change notification settings - Fork 1
/
heap.cc
61 lines (48 loc) · 1.01 KB
/
heap.cc
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
#include "heap.hh"
#include <algorithm>
#include <assert.h>
Heap::Heap(TStringIndex max_size):
used(0)
{
assert(max_size);
heap.reserve(max_size);
}
void Heap::add(HeapPair item)
{
assert(used <= heap.size());
if (used == heap.size()) {
heap.push_back(item);
} else {
heap[used] = item;
}
if (used++) {
std::push_heap(heap.begin(), heap.begin() + used);
}
}
HeapPair Heap::get_max() const
{
assert(used);
assert(used <= heap.size());
return heap[0];
}
void Heap::del_max()
{
assert(used);
assert(used <= heap.size());
if (used > 1) {
std::pop_heap(heap.begin(), heap.begin() + used);
}
--used;
}
void Heap::replace_max(TStringIndex new_key)
{
assert(used);
assert(used <= heap.size());
if (used == 1) {
heap[0].set_key(new_key);
} else {
std::pop_heap(heap.begin(), heap.begin() + used);
heap[used - 1].set_key(new_key);
std::push_heap(heap.begin(), heap.begin() + used);
}
}