33 template <
typename KeyType>
40 element(KeyType key,
size_t idx): key(key), idx(idx) {}
42 std::vector<element> backing;
43 std::vector<size_t> locs;
46 heap_indexed(): backing(1,element(KeyType(),0)), locs(0) {}
50 backing.resize(1,element(KeyType(),0));
55 inline size_t size()
const
57 return backing.size() - 1;
59 inline bool contains(
size_t idx)
const
61 if (idx < locs.size() && locs[idx])
68 inline KeyType key_of(
size_t idx)
const
70 size_t loc = locs[idx];
71 return backing[loc].key;
77 inline void up_heap(
size_t idx, KeyType key,
size_t loc)
82 size_t loc_parent = loc / 2;
84 if (!loc_parent || backing[loc_parent].key <= key)
87 size_t idx_parent = backing[loc_parent].idx;
88 std::swap(backing[loc_parent], backing[loc]);
89 std::swap(locs[idx_parent], locs[idx]);
97 inline void down_heap(
size_t idx, KeyType key,
size_t loc)
102 size_t loc_left = 2*loc;
103 size_t loc_right = 2*loc+1;
105 size_t loc_min = loc;
106 KeyType key_min = key;
107 if (loc_left < backing.size() && backing[loc_left].key < key_min)
110 key_min = backing[loc_left].key;
112 if (loc_right < backing.size() && backing[loc_right].key < key_min)
115 key_min = backing[loc_right].key;
120 size_t idx_min = backing[loc_min].idx;
122 std::swap(backing[loc], backing[loc_min]);
123 std::swap(locs[idx], locs[idx_min]);
129 inline void insert(
size_t idx, KeyType key)
132 if (locs.size() < idx+1)
133 locs.resize(idx+1, 0);
135 size_t loc = backing.size();
136 backing.push_back(element(key,idx));
139 up_heap(idx,key,loc);
143 inline void update(
size_t idx, KeyType key)
145 size_t loc = locs[idx];
146 if (key < backing[loc].key)
148 backing[loc].key = key;
149 up_heap(idx, key, loc);
152 if (key > backing[loc].key)
154 backing[loc].key = key;
155 down_heap(idx, key, loc);
161 inline void remove(
size_t idx)
163 size_t loc = locs[idx];
164 KeyType key = backing[loc].key;
165 size_t loc_last = backing.size()-1;
174 size_t idx_last = backing[loc_last].idx;
175 backing[loc] = backing[loc_last];
177 locs[idx_last] = loc;
180 if (backing[loc].key < key)
181 up_heap(idx_last, backing[loc].key, loc);
182 if (backing[loc].key > key)
183 down_heap(idx_last, backing[loc].key, loc);
187 inline KeyType top_key()
const
189 return backing[1].key;
191 inline size_t top_idx()
const
193 return backing[1].idx;
195 inline void remove_min()
202 backing[1] = backing[backing.size()-1];
203 locs[backing[1].idx] = 1;
209 down_heap(backing[1].idx, backing[1].key, 1);
215 for (
size_t ui=0; ui<backing.size(); ui++)
216 printf(
" %u:(%.1f,%u)", ui, backing[ui].key, backing[ui].idx);
219 for (
size_t ui=0; ui<locs.size(); ui++)
220 printf(
" %u:%u", ui, locs[ui]);
Binary min-heap with index lookups.
Definition: heap_indexed.h:34