forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary_heap.cpp
93 lines (81 loc) · 2.03 KB
/
binary_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
#include <bits/stdc++.h>
using namespace std;
template <class T>
struct binary_heap {
vector<T> heap;
vector<int> pos2Id;
vector<int> id2Pos;
int size;
binary_heap() : size(0) {}
binary_heap(int n) : heap(n), pos2Id(n), id2Pos(n), size(0) {}
void add(int id, T value) {
heap[size] = value;
pos2Id[size] = id;
id2Pos[id] = size;
up(size++);
}
int remove_min() {
int removedId = pos2Id[0];
heap[0] = heap[--size];
pos2Id[0] = pos2Id[size];
id2Pos[pos2Id[0]] = 0;
down(0);
return removedId;
}
void remove(int id) {
int pos = id2Pos[id];
pos2Id[pos] = pos2Id[--size];
id2Pos[pos2Id[pos]] = pos;
changePriority(pos2Id[pos], heap[size]);
}
void changePriority(int id, T value) {
int pos = id2Pos[id];
if (heap[pos] < value) {
heap[pos] = value;
down(pos);
} else if (heap[pos] > value) {
heap[pos] = value;
up(pos);
}
}
void up(int pos) {
while (pos > 0) {
int parent = (pos - 1) / 2;
if (heap[pos] >= heap[parent])
break;
exchange(pos, parent);
pos = parent;
}
}
void down(int pos) {
while (true) {
int child = 2 * pos + 1;
if (child >= size)
break;
if (child + 1 < size && heap[child + 1] < heap[child])
++child;
if (heap[pos] <= heap[child])
break;
exchange(pos, child);
pos = child;
}
}
void exchange(int i, int j) {
swap(heap[i], heap[j]);
swap(pos2Id[i], pos2Id[j]);
id2Pos[pos2Id[i]] = i;
id2Pos[pos2Id[j]] = j;
}
};
// usage example
int main() {
binary_heap<int> h(5);
h.add(0, 50);
h.add(1, 30);
h.add(2, 40);
h.changePriority(0, 20);
h.remove(1);
while (h.size) {
cout << h.remove_min() << endl;
}
}