Skip to content

Commit c4d6146

Browse files
committed
refactor: simplify priority queue of updates
Replace the apply(&DS::join, ...) indirection with a direct lambda, rename internal containers to describe their role, and document the non-obvious invariants. Behavior and complexity are unchanged.
1 parent b9d7aed commit c4d6146

1 file changed

Lines changed: 16 additions & 11 deletions

File tree

library/data_structures_[l,r)/uncommon/priority_queue_of_updates.hpp

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,24 +30,29 @@ template<class DS, class... ARGS> struct pq_updates {
3030
//! store popped updates; size of `upd_st`, `mp` member
3131
//! variables decreases by 1
3232
void pop_update() {
33-
vector<upd> extra;
33+
// shortest suffix [idx, sz(upd_st)) of which at least
34+
// half is `top`, the highest priority updates
35+
vector<upd> top;
3436
int idx = sz(upd_st) - 1, lowest_pri = INT_MAX;
3537
for (auto it = rbegin(mp);
36-
2 * sz(extra) < sz(upd_st) - idx; it++) {
37-
auto [pri, idx_sk] = *it;
38-
extra.push_back(upd_st[idx_sk]);
39-
idx = min(idx, idx_sk), lowest_pri = pri;
38+
2 * sz(top) < sz(upd_st) - idx; it++) {
39+
auto [pri, i] = *it;
40+
top.push_back(upd_st[i]);
41+
idx = min(idx, i), lowest_pri = pri;
4042
}
41-
auto it = remove_if(idx + all(upd_st), [&](auto& cur) {
42-
return cur.second->first >= lowest_pri;
43-
});
44-
ranges::reverse_copy(extra, it);
4543
rep(i, idx, sz(upd_st)) ds.undo();
44+
// move `top` to the end of the suffix, by decreasing
45+
// priority, so the max is on top
46+
auto mid = remove_if(idx + all(upd_st),
47+
[&](const upd& u) {
48+
return u.second->first >= lowest_pri;
49+
});
50+
ranges::reverse_copy(top, mid);
4651
upd_st.pop_back();
4752
mp.erase(prev(end(mp)));
4853
rep(i, idx, sz(upd_st)) {
49-
apply(&DS::join,
50-
tuple_cat(make_tuple(&ds), upd_st[i].first));
54+
apply([&](const ARGS&... args) { ds.join(args...); },
55+
upd_st[i].first);
5156
upd_st[i].second->second = i;
5257
}
5358
}

0 commit comments

Comments
 (0)