Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
HLD.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
90#ifndef HLD_H
91#define HLD_H
92
93# include <ah-graph-concepts.H>
94
95# include <algorithm>
96# include <cstddef>
97# include <limits>
98# include <type_traits>
99# include <utility>
100
101# include <ah-errors.H>
102# include <tpl_array.H>
103# include <tpl_dynListStack.H>
104# include <tpl_dynMapOhash.H>
105# include <tpl_dynMapTree.H>
106# include <tpl_graph.H>
107# include <tpl_segment_tree.H>
108
109namespace Aleph
110{
111 namespace hld_detail
112 {
121 template <AlephGraph GT, ArcFilter<GT> SA>
123 {
124 // moved-from: tested through HLD_Sum, which keeps it (Tests/moved_from_graphs_test.cc)
125 public:
126 using Node = typename GT::Node;
127 using Arc = typename GT::Arc;
128
129 static constexpr size_t NONE = std::numeric_limits<size_t>::max();
130
131 private:
132 using Pair_Key = std::pair<size_t, size_t>;
133
134 const GT * graph_ = nullptr;
135 SA sa_;
136 Node * root_ = nullptr;
137 size_t root_id_ = NONE;
138
139 size_t n_ = 0;
140
143
148
149 // HLD-specific arrays
150 Array<size_t> pos_; // flat position in segment tree
151 Array<size_t> chain_head_; // head of the chain containing this node
152 Array<size_t> tin_; // entry time (same as pos_ for HLD)
153 Array<size_t> tout_; // exit time
154
155 size_t num_chains_ = 0;
156
157 static Pair_Key normalize_pair(size_t u, size_t v) noexcept
158 {
159 if (u > v)
160 std::swap(u, v);
161 return std::make_pair(u, v);
162 }
163
165 {
167
168 if (n_ == 0)
169 {
170 ah_domain_error_if(root_ != nullptr)
171 << "HLD_Tree_Data: root node provided but graph is empty";
172 return;
173 }
174
176 {
178 node_to_id_.swap(tmp);
179 }
180
181 size_t next_id = 0;
182 for (Node_Iterator<GT> it(*graph_); it.has_curr(); it.next_ne())
183 {
184 Node * p = it.get_curr();
185 id_to_node_(next_id) = p;
186 node_to_id_.insert(p, next_id);
187 ++next_id;
188 }
189
190 ah_runtime_error_unless(next_id == n_)
191 << "HLD_Tree_Data: failed to index all graph nodes";
192
193 if (root_ == nullptr)
194 root_ = id_to_node_(0);
195
197 << "HLD_Tree_Data: root node does not belong to graph";
198
200 }
201
203 {
204 if (n_ == 0)
205 return;
206
207 adjacency_.empty();
208 adjacency_.reserve(n_);
209 for (size_t i = 0; i < n_; ++i)
210 adjacency_.append(Array<size_t>());
211
212 DynMapTree<Pair_Key, char> unique_edges;
213 size_t edge_count = 0;
214
215 for (Arc_Iterator<GT, SA> it(*graph_, sa_); it.has_curr(); it.next_ne())
216 {
217 Arc * a = it.get_curr_ne();
218 Node * src = graph_->get_src_node(a);
219 Node * tgt = graph_->get_tgt_node(a);
220
221 const auto * src_item = node_to_id_.search(src);
222 const auto * tgt_item = node_to_id_.search(tgt);
223
224 ah_runtime_error_unless(src_item != nullptr and tgt_item != nullptr)
225 << "HLD_Tree_Data: arc endpoint is not indexed";
226
227 const size_t u = src_item->second;
228 const size_t v = tgt_item->second;
229
230 ah_domain_error_if(u == v)
231 << "HLD_Tree_Data: self-loop detected in filtered graph";
232
233 const Pair_Key key = normalize_pair(u, v);
234 ah_domain_error_if(unique_edges.search(key) != nullptr)
235 << "HLD_Tree_Data: parallel/duplicate edge detected in filtered graph";
236
237 unique_edges.insert(key, 1);
238 ++edge_count;
239 }
240
241 ah_domain_error_if(edge_count != n_ - 1)
242 << "HLD_Tree_Data: filtered graph is not a tree (expected "
243 << (n_ - 1) << " edges, got " << edge_count << ")";
244
245 for (typename DynMapTree<Pair_Key, char>::Iterator it(unique_edges);
246 it.has_curr(); it.next_ne())
247 {
248 const auto & [fst, snd] = it.get_curr();
249 const size_t u = fst.first;
250 const size_t v = fst.second;
251 adjacency_(u).append(v);
252 adjacency_(v).append(u);
253 }
254 }
255
257 {
258 if (n_ == 0)
259 return;
260
264
265 for (size_t i = 0; i < n_; ++i)
266 {
267 parent_(i) = NONE;
268 subtree_size_(i) = 1;
269 }
270
272 for (size_t i = 0; i < n_; ++i)
273 visited(i) = 0;
274
275 struct Frame
276 {
277 size_t node;
278 size_t parent;
279 size_t next_child;
280 };
281
283
284 size_t visited_count = 1;
285 visited(root_id_) = 1;
286 depth_(root_id_) = 0;
288
289 stack.push({root_id_, NONE, 0});
290
291 while (not stack.is_empty())
292 {
293 auto & fr = stack.top();
294
295 if (fr.next_child == adjacency_(fr.node).size())
296 {
297 // All children processed; accumulate size into parent.
298 // Save fr.node before pop() invalidates the reference.
299 const size_t done = fr.node;
300 (void) stack.pop();
301 if (not stack.is_empty())
302 subtree_size_(stack.top().node) += subtree_size_(done);
303 continue;
304 }
305
306 const size_t nxt = adjacency_(fr.node)(fr.next_child++);
307 if (nxt == fr.parent)
308 continue;
309
310 ah_domain_error_if(visited(nxt))
311 << "HLD_Tree_Data: filtered graph is not acyclic";
312
313 visited(nxt) = 1;
314 ++visited_count;
315
316 parent_(nxt) = fr.node;
317 depth_(nxt) = depth_(fr.node) + 1;
318
319 stack.push({nxt, fr.node, 0});
320 }
321
322 ah_domain_error_if(visited_count != n_)
323 << "HLD_Tree_Data: filtered graph is not connected";
324 }
325
327 {
328 if (n_ == 0)
329 return;
330
331 for (size_t u = 0; u < n_; ++u)
332 {
333 auto & adj = adjacency_(u);
334 if (adj.size() <= 1)
335 continue;
336
337 // Find the child with the largest subtree_size
338 size_t best_idx = NONE;
339 size_t best_size = 0;
340
341 for (size_t i = 0; i < adj.size(); ++i)
342 {
343 const size_t v = adj(i);
344 if (v == parent_(u))
345 continue;
346 if (subtree_size_(v) > best_size)
347 {
348 best_size = subtree_size_(v);
349 best_idx = i;
350 }
351 }
352
353 if (best_idx == NONE)
354 continue;
355
356 // Swap the heavy child to position 0 (or the first non-parent)
357 // Find the first non-parent position
358 size_t first_child_pos = 0;
359 if (adj(0) == parent_(u))
360 first_child_pos = 1;
361
362 if (best_idx != first_child_pos)
363 std::swap(adj(best_idx), adj(first_child_pos));
364 }
365 }
366
368 {
369 if (n_ == 0)
370 return;
371
376
377 struct Frame
378 {
379 size_t node;
380 size_t parent;
381 size_t next_child;
382 size_t head;
383 };
384
386
387 size_t timer = 0;
388 num_chains_ = 0;
389
390 // Root starts a new chain
391 pos_(root_id_) = timer;
392 tin_(root_id_) = timer;
394 ++timer;
395 ++num_chains_;
396
397 stack.push({root_id_, NONE, 0, root_id_});
398
399 while (not stack.is_empty())
400 {
401 auto & fr = stack.top();
402
403 if (fr.next_child == adjacency_(fr.node).size())
404 {
405 tout_(fr.node) = timer - 1;
406 (void) stack.pop();
407 continue;
408 }
409
410 const size_t nxt = adjacency_(fr.node)(fr.next_child);
411 ++fr.next_child;
412
413 if (nxt == fr.parent)
414 continue;
415
416 // Determine if this is a heavy or light child
417 // The heavy child is the first non-parent child in adjacency
418 // (after reordering)
419 bool is_heavy = false;
420 {
421 const auto & adj = adjacency_(fr.node);
422 size_t first_child_pos = 0;
423 if (adj.size() > 0 and adj(0) == fr.parent)
424 first_child_pos = 1;
425 if (first_child_pos < adj.size() and adj(first_child_pos) == nxt)
426 is_heavy = true;
427 }
428
429 if (is_heavy)
430 {
431 chain_head_(nxt) = fr.head;
432 }
433 else
434 {
435 chain_head_(nxt) = nxt;
436 ++num_chains_;
437 }
438
439 pos_(nxt) = timer;
440 tin_(nxt) = timer;
441 ++timer;
442
443 stack.push({nxt, fr.node, 0, chain_head_(nxt)});
444 }
445 }
446
447 void check_id(const size_t id, const char * where) const
448 {
450 << where << ": id=" << id << " is out of range [0, " << n_ << ")";
451 }
452
453 public:
454 HLD_Tree_Data(const GT & g, Node * root, SA sa = SA())
455 : graph_(&g), sa_(std::move(sa)), root_(root)
456 {
457 index_nodes();
462 }
463
467 HLD_Tree_Data(const HLD_Tree_Data & other) = default;
468
479 HLD_Tree_Data(HLD_Tree_Data && other) noexcept(std::is_nothrow_move_constructible_v<SA>)
480 : graph_(std::exchange(other.graph_, nullptr)), sa_(std::move(other.sa_)),
481 root_(std::exchange(other.root_, nullptr)),
482 root_id_(std::exchange(other.root_id_, NONE)), n_(std::exchange(other.n_, 0)),
483 id_to_node_(std::move(other.id_to_node_)), node_to_id_(std::move(other.node_to_id_)),
484 adjacency_(std::move(other.adjacency_)), parent_(std::move(other.parent_)),
485 depth_(std::move(other.depth_)), subtree_size_(std::move(other.subtree_size_)),
486 pos_(std::move(other.pos_)), chain_head_(std::move(other.chain_head_)),
487 tin_(std::move(other.tin_)), tout_(std::move(other.tout_)),
488 num_chains_(std::exchange(other.num_chains_, 0))
489 {}
490
495 HLD_Tree_Data & operator = (const HLD_Tree_Data & other) = default;
496
502 HLD_Tree_Data & operator = (HLD_Tree_Data && other) noexcept(noexcept(swap(other)))
503 {
504 swap(other);
505 return *this;
506 }
507
515 void swap(HLD_Tree_Data & other) noexcept(std::is_nothrow_swappable_v<SA>)
516 {
517 swap_filter(other);
518 swap_but_filter(other);
519 }
520
526 void swap_filter(HLD_Tree_Data & other) noexcept(std::is_nothrow_swappable_v<SA>)
527 {
528 // the swap that the specification evaluates: that of SA, found by
529 // its arguments, else std::swap()
530 using std::swap;
531 swap(sa_, other.sa_);
532 }
533
538 void swap_but_filter(HLD_Tree_Data & other) noexcept
539 {
540 std::swap(graph_, other.graph_);
541 std::swap(root_, other.root_);
542 std::swap(root_id_, other.root_id_);
543 std::swap(n_, other.n_);
544 id_to_node_.swap(other.id_to_node_);
545 node_to_id_.swap(other.node_to_id_);
546 adjacency_.swap(other.adjacency_);
547 parent_.swap(other.parent_);
548 depth_.swap(other.depth_);
549 subtree_size_.swap(other.subtree_size_);
550 pos_.swap(other.pos_);
551 chain_head_.swap(other.chain_head_);
552 tin_.swap(other.tin_);
553 tout_.swap(other.tout_);
554 std::swap(num_chains_, other.num_chains_);
555 }
556
557 [[nodiscard]] size_t size() const noexcept { return n_; }
558 [[nodiscard]] bool is_empty() const noexcept { return n_ == 0; }
559 [[nodiscard]] Node * root() const noexcept { return root_; }
560 [[nodiscard]] size_t root_id() const noexcept { return root_id_; }
561
562 [[nodiscard]] const Array<Node *> & id_to_node() const noexcept { return id_to_node_; }
563 [[nodiscard]] const Array<size_t> & parent() const noexcept { return parent_; }
564 [[nodiscard]] const Array<size_t> & depth() const noexcept { return depth_; }
565 [[nodiscard]] const Array<size_t> & subtree_size() const noexcept { return subtree_size_; }
566 [[nodiscard]] const Array<size_t> & pos() const noexcept { return pos_; }
567 [[nodiscard]] const Array<size_t> & chain_head() const noexcept { return chain_head_; }
568 [[nodiscard]] const Array<size_t> & tin() const noexcept { return tin_; }
569 [[nodiscard]] const Array<size_t> & tout() const noexcept { return tout_; }
570 [[nodiscard]] size_t num_chains() const noexcept { return num_chains_; }
571
572 [[nodiscard]] size_t id_of(const Node * node) const
573 {
574 ah_invalid_argument_if(node == nullptr)
575 << "HLD_Tree_Data::id_of: null node";
576
577 const auto * item = node_to_id_.search(const_cast<Node *>(node));
578 ah_domain_error_if(item == nullptr)
579 << "HLD_Tree_Data::id_of: node does not belong to graph";
580
581 return item->second;
582 }
583
584 [[nodiscard]] Node * node_of(const size_t id) const
585 {
586 check_id(id, "HLD_Tree_Data::node_of");
587 return id_to_node_(id);
588 }
589
590 void validate_id(const size_t id, const char * where) const
591 {
592 check_id(id, where);
593 }
594 };
595 } // namespace hld_detail
596
597
621 template <AlephGraph GT, typename T, class Op, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
622 requires SegmentTreeOp<Op, T>
624 {
625 public:
626 using Node = typename GT::Node;
627
628 private:
630 static constexpr size_t NONE = Topology::NONE;
631
634 Op op_;
636
637 [[nodiscard]] size_t n() const noexcept { return topology_.size(); }
638
639 void ensure_not_empty(const char * where) const
640 {
641 ah_domain_error_if(is_empty()) << where << ": tree is empty";
642 }
643
645 template <class NodeValueFn>
646 void build_segment_tree(NodeValueFn && node_value)
647 {
648 if (is_empty())
649 return;
650
651 auto flat = Array<T>::create(n());
652 for (size_t i = 0; i < n(); ++i)
653 flat(i) = identity_;
654
655 for (size_t id = 0; id < n(); ++id)
656 {
657 const size_t p = topology_.pos()(id);
658 flat(p) = node_value(topology_.id_to_node()(id));
659 }
660
661 Gen_Segment_Tree<T, Op> real_seg(flat, identity_, op_);
662 seg_.swap(real_seg);
663 }
664
665 public:
676 template <class NodeValueFn>
677 Gen_HLD(const GT & g, Node * root, NodeValueFn && node_value,
678 const T & identity, Op oper = Op(), SA sa = SA())
679 : topology_(g, root, std::move(sa)),
680 identity_(identity),
681 op_(oper),
682 seg_(1, identity, identity, oper)
683 {
684 build_segment_tree(std::forward<NodeValueFn>(node_value));
685 }
686
688 template <class NodeValueFn>
689 Gen_HLD(const GT & g, NodeValueFn && node_value,
690 const T & identity, Op oper = Op(), SA sa = SA())
691 : topology_(g, nullptr, std::move(sa)),
692 identity_(identity),
693 op_(oper),
694 seg_(1, identity, identity, oper)
695 {
696 build_segment_tree(std::forward<NodeValueFn>(node_value));
697 }
698
702 Gen_HLD(const Gen_HLD & other) = default;
703
712 Gen_HLD(Gen_HLD && other) = default;
713
718 Gen_HLD & operator = (const Gen_HLD & other) = default;
719
731 Gen_HLD & operator = (Gen_HLD && other) noexcept(noexcept(swap(other)))
732 {
733 swap(other);
734 return *this;
735 }
736
747 void swap(Gen_HLD & other)
748 noexcept(std::is_nothrow_swappable_v<T> and std::is_nothrow_swappable_v<Op>
749 and std::is_nothrow_swappable_v<SA>)
750 {
751 // The swaps that the specification evaluates: found by the
752 // arguments, else std::swap()
753 using std::swap;
754 if constexpr (std::is_nothrow_swappable_v<T> and std::is_nothrow_swappable_v<Op>
755 and std::is_nothrow_swappable_v<SA>)
756 {
757 // None may throw: the order cannot be seen, and that of the
758 // members keeps the code of an identity that has state, an int
759 swap(op_, other.op_);
760 topology_.swap(other.topology_);
761 swap(identity_, other.identity_);
762 seg_.swap(other.seg_);
763 }
764 else
765 {
766 // The rest of the topologies, which cannot throw, goes last, so
767 // that no topology is left without its segment tree
769 topology_.swap_but_filter(other.topology_);
770 }
771 }
772
773 private:
774 // The operations, the values, the filters of the topologies and the
775 // segment trees, whose swap is all or none, with the swaps that the
776 // specification of swap() evaluates, all or none: if one throws, those
777 // before it are exchanged back
779 {
780 using std::swap;
781 int done = 0;
782 try
783 {
784 swap(op_, other.op_);
785 ++done;
786 swap(identity_, other.identity_);
787 ++done;
789 ++done;
790 seg_.swap(other.seg_);
791 }
792 catch (...)
793 {
794 if (done > 2)
796 if (done > 1)
797 swap(identity_, other.identity_);
798 if (done > 0)
799 swap(op_, other.op_);
800 throw;
801 }
802 }
803
804 public:
806 [[nodiscard]] size_t size() const noexcept { return topology_.size(); }
807
809 [[nodiscard]] bool is_empty() const noexcept { return topology_.is_empty(); }
810
812 [[nodiscard]] Node * root() const noexcept { return topology_.root(); }
813
815 [[nodiscard]] size_t root_id() const noexcept { return topology_.root_id(); }
816
818 [[nodiscard]] Node * node_of(const size_t id) const
819 {
820 return topology_.node_of(id);
821 }
822
824 [[nodiscard]] size_t id_of(const Node * node) const
825 {
826 return topology_.id_of(node);
827 }
828
830 [[nodiscard]] size_t position(const size_t id) const
831 {
832 topology_.validate_id(id, "Gen_HLD::position");
833 return topology_.pos()(id);
834 }
835
837 [[nodiscard]] size_t chain_head_id(const size_t id) const
838 {
839 topology_.validate_id(id, "Gen_HLD::chain_head_id");
840 return topology_.chain_head()(id);
841 }
842
844 [[nodiscard]] size_t depth_of_id(const size_t id) const
845 {
846 topology_.validate_id(id, "Gen_HLD::depth_of_id");
847 return topology_.depth()(id);
848 }
849
851 [[nodiscard]] size_t depth_of(const Node * node) const
852 {
853 return depth_of_id(id_of(node));
854 }
855
857 [[nodiscard]] size_t subtree_size_of_id(const size_t id) const
858 {
859 topology_.validate_id(id, "Gen_HLD::subtree_size_of_id");
860 return topology_.subtree_size()(id);
861 }
862
864 [[nodiscard]] size_t subtree_size_of(const Node * node) const
865 {
866 return subtree_size_of_id(id_of(node));
867 }
868
870 [[nodiscard]] size_t parent_id(const size_t id) const
871 {
872 topology_.validate_id(id, "Gen_HLD::parent_id");
873 return topology_.parent()(id);
874 }
875
877 [[nodiscard]] Node * parent_of(const Node * node) const
878 {
879 const size_t pid = parent_id(id_of(node));
880 return pid == NONE ? nullptr : node_of(pid);
881 }
882
884 [[nodiscard]] size_t num_chains() const noexcept
885 {
886 return topology_.num_chains();
887 }
888
889 // ------------------------------------------------------------------
890 // Path queries
891 // ------------------------------------------------------------------
892
902 [[nodiscard]] T path_query_id(size_t u, size_t v) const
903 {
904 ensure_not_empty("Gen_HLD::path_query_id");
905 topology_.validate_id(u, "Gen_HLD::path_query_id");
906 topology_.validate_id(v, "Gen_HLD::path_query_id");
907
908 T result = identity_;
909
910 while (topology_.chain_head()(u) != topology_.chain_head()(v))
911 {
912 // Move the deeper chain head up
913 if (topology_.depth()(topology_.chain_head()(u)) <
915 std::swap(u, v);
916
917 // Query the segment from chain_head(u) to u
918 const size_t head = topology_.chain_head()(u);
919 result = op_(result, seg_.query(topology_.pos()(head),
920 topology_.pos()(u)));
921 u = topology_.parent()(head);
922 }
923
924 // u and v are now on the same chain
925 if (topology_.depth()(u) > topology_.depth()(v))
926 std::swap(u, v);
927
928 result = op_(result, seg_.query(topology_.pos()(u),
929 topology_.pos()(v)));
930 return result;
931 }
932
934 [[nodiscard]] T path_query(const Node * u, const Node * v) const
935 {
936 return path_query_id(id_of(u), id_of(v));
937 }
938
944 [[nodiscard]] T path_query_edges_id(size_t u, size_t v) const
945 {
946 ensure_not_empty("Gen_HLD::path_query_edges_id");
947 topology_.validate_id(u, "Gen_HLD::path_query_edges_id");
948 topology_.validate_id(v, "Gen_HLD::path_query_edges_id");
949
950 T result = identity_;
951
952 while (topology_.chain_head()(u) != topology_.chain_head()(v))
953 {
954 if (topology_.depth()(topology_.chain_head()(u)) <
956 std::swap(u, v);
957
958 const size_t head = topology_.chain_head()(u);
959 result = op_(result, seg_.query(topology_.pos()(head),
960 topology_.pos()(u)));
961 u = topology_.parent()(head);
962 }
963
964 if (topology_.depth()(u) > topology_.depth()(v))
965 std::swap(u, v);
966
967 // Skip the LCA node (u) for edge-weighted queries
968 if (u != v)
969 result = op_(result, seg_.query(topology_.pos()(u) + 1,
970 topology_.pos()(v)));
971
972 return result;
973 }
974
976 [[nodiscard]] T path_query_edges(const Node * u, const Node * v) const
977 {
978 return path_query_edges_id(id_of(u), id_of(v));
979 }
980
981 // ------------------------------------------------------------------
982 // Subtree queries
983 // ------------------------------------------------------------------
984
989 [[nodiscard]] T subtree_query_id(const size_t v) const
990 {
991 ensure_not_empty("Gen_HLD::subtree_query_id");
992 topology_.validate_id(v, "Gen_HLD::subtree_query_id");
993
994 const size_t l = topology_.pos()(v);
995 const size_t r = l + topology_.subtree_size()(v) - 1;
996 return seg_.query(l, r);
997 }
998
1000 [[nodiscard]] T subtree_query(const Node * v) const
1001 {
1002 return subtree_query_id(id_of(v));
1003 }
1004
1005 // ------------------------------------------------------------------
1006 // Point update
1007 // ------------------------------------------------------------------
1008
1014 void point_update_id(const size_t v, const T & new_value)
1015 {
1016 ensure_not_empty("Gen_HLD::point_update_id");
1017 topology_.validate_id(v, "Gen_HLD::point_update_id");
1018
1019 seg_.set(topology_.pos()(v), new_value);
1020 }
1021
1023 void point_update(const Node * v, const T & new_value)
1024 {
1025 point_update_id(id_of(v), new_value);
1026 }
1027
1028 // ------------------------------------------------------------------
1029 // LCA queries (free from chain walk)
1030 // ------------------------------------------------------------------
1031
1033 [[nodiscard]] size_t lca_id(size_t u, size_t v) const
1034 {
1035 ensure_not_empty("Gen_HLD::lca_id");
1036 topology_.validate_id(u, "Gen_HLD::lca_id");
1037 topology_.validate_id(v, "Gen_HLD::lca_id");
1038
1039 while (topology_.chain_head()(u) != topology_.chain_head()(v))
1040 {
1041 if (topology_.depth()(topology_.chain_head()(u)) <
1043 std::swap(u, v);
1044
1046 }
1047
1048 return topology_.depth()(u) <= topology_.depth()(v) ? u : v;
1049 }
1050
1052 [[nodiscard]] Node * lca(const Node * u, const Node * v) const
1053 {
1054 return node_of(lca_id(id_of(u), id_of(v)));
1055 }
1056
1057 // ------------------------------------------------------------------
1058 // Distance queries
1059 // ------------------------------------------------------------------
1060
1062 [[nodiscard]] size_t distance_id(const size_t u, const size_t v) const
1063 {
1064 const size_t a = lca_id(u, v);
1065 return topology_.depth()(u) + topology_.depth()(v)
1066 - 2 * topology_.depth()(a);
1067 }
1068
1070 [[nodiscard]] size_t distance(const Node * u, const Node * v) const
1071 {
1072 return distance_id(id_of(u), id_of(v));
1073 }
1074
1075 // ------------------------------------------------------------------
1076 // Decomposition accessors (for power users)
1077 // ------------------------------------------------------------------
1078
1083 [[nodiscard]] const Array<size_t> & position_array() const noexcept
1084 {
1085 return topology_.pos();
1086 }
1087
1093 [[nodiscard]] const Array<size_t> & chain_head_array() const noexcept
1094 {
1095 return topology_.chain_head();
1096 }
1097
1099 [[nodiscard]] const Array<size_t> & depth_array() const noexcept
1100 {
1101 return topology_.depth();
1102 }
1103
1105 [[nodiscard]] const Array<size_t> & subtree_size_array() const noexcept
1106 {
1107 return topology_.subtree_size();
1108 }
1109
1111 [[nodiscard]] const Array<size_t> & parent_array() const noexcept
1112 {
1113 return topology_.parent();
1114 }
1115
1117 [[nodiscard]] T get_value_at_id(const size_t id) const
1118 {
1119 topology_.validate_id(id, "Gen_HLD::get_value_at_id");
1120 return seg_.get(topology_.pos()(id));
1121 }
1122
1124 [[nodiscard]] T get_value(const Node * v) const
1125 {
1126 return get_value_at_id(id_of(v));
1127 }
1128 };
1129
1130
1131 // ====================================================================
1132 // Convenience aliases
1133 // ====================================================================
1134
1143 template <AlephGraph GT, typename T, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1144 struct HLD_Sum : public Gen_HLD<GT, T, Aleph::plus<T>, SA>
1145 {
1147 using Node = typename GT::Node;
1148
1149 template <class NodeValueFn>
1150 HLD_Sum(const GT & g, Node * root, NodeValueFn && nv, SA sa = SA())
1151 : Base(g, root, std::forward<NodeValueFn>(nv),
1152 T(), Aleph::plus<T>(), std::move(sa))
1153 {}
1154
1155 template <class NodeValueFn>
1156 HLD_Sum(const GT & g, NodeValueFn && nv, SA sa = SA())
1157 : Base(g, std::forward<NodeValueFn>(nv),
1158 T(), Aleph::plus<T>(), std::move(sa))
1159 {}
1160 };
1161
1170 template <AlephGraph GT, typename T, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1171 struct HLD_Max : public Gen_HLD<GT, T, Max_Op<T>, SA>
1172 {
1174 using Node = typename GT::Node;
1175
1176 template <class NodeValueFn>
1177 HLD_Max(const GT & g, Node * root, NodeValueFn && nv, SA sa = SA())
1178 : Base(g, root, std::forward<NodeValueFn>(nv),
1179 std::numeric_limits<T>::lowest(), Max_Op<T>(), std::move(sa))
1180 {}
1181
1182 template <class NodeValueFn>
1183 HLD_Max(const GT & g, NodeValueFn && nv, SA sa = SA())
1184 : Base(g, std::forward<NodeValueFn>(nv),
1185 std::numeric_limits<T>::lowest(), Max_Op<T>(), std::move(sa))
1186 {}
1187 };
1188
1197 template <AlephGraph GT, typename T, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1198 struct HLD_Min : public Gen_HLD<GT, T, Min_Op<T>, SA>
1199 {
1201 using Node = typename GT::Node;
1202
1203 template <class NodeValueFn>
1204 HLD_Min(const GT & g, Node * root, NodeValueFn && nv, SA sa = SA())
1205 : Base(g, root, std::forward<NodeValueFn>(nv),
1206 std::numeric_limits<T>::max(), Min_Op<T>(), std::move(sa))
1207 {}
1208
1209 template <class NodeValueFn>
1210 HLD_Min(const GT & g, NodeValueFn && nv, SA sa = SA())
1211 : Base(g, std::forward<NodeValueFn>(nv),
1212 std::numeric_limits<T>::max(), Min_Op<T>(), std::move(sa))
1213 {}
1214 };
1215
1216} // namespace Aleph
1217
1218#endif // HLD_H
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
Definition ah-errors.H:399
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
C++20 concepts for the protocol shared by graph algorithms.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
static Array create(const size_t n)
Create an array with n logical elements.
Definition tpl_array.H:245
Dynamic stack of elements of generic type T based on a singly linked list.
T & top()
Return a modifiable reference to the top item of the stack.
bool is_empty() const noexcept
Check if the stack is empty.
T pop()
Remove and return the top item of the stack.
T & push(const T &data)
Push an item by copy onto the top of the stack.
Generic key-value map implemented on top of a binary search tree.
typename Base::Iterator Iterator
Pair * search(const Key &key) noexcept(nothrow_search)
Collect all keys.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Heavy-Light Decomposition with segment tree for path/subtree queries.
Definition HLD.H:624
static constexpr size_t NONE
Definition HLD.H:630
void point_update_id(const size_t v, const T &new_value)
Point update by node ID: set value to new_value.
Definition HLD.H:1014
void swap_but_topology_storage(Gen_HLD &other)
Definition HLD.H:778
void swap(Gen_HLD &other) noexcept(std::is_nothrow_swappable_v< T > and std::is_nothrow_swappable_v< Op > and std::is_nothrow_swappable_v< SA >)
Exchange in O(1) this HLD and another.
Definition HLD.H:747
size_t distance(const Node *u, const Node *v) const
Number of edges between two nodes in O(log n).
Definition HLD.H:1070
T path_query(const Node *u, const Node *v) const
Path query by node pointers in O(log^2 n).
Definition HLD.H:934
T path_query_id(size_t u, size_t v) const
Path query by node IDs in O(log^2 n).
Definition HLD.H:902
size_t chain_head_id(const size_t id) const
Head of the chain containing node id.
Definition HLD.H:837
Node * node_of(const size_t id) const
Map an internal ID back to a Node pointer.
Definition HLD.H:818
size_t depth_of_id(const size_t id) const
Depth of node id from root.
Definition HLD.H:844
size_t subtree_size_of_id(const size_t id) const
Subtree size of node id.
Definition HLD.H:857
size_t num_chains() const noexcept
Number of heavy chains in the decomposition.
Definition HLD.H:884
T get_value(const Node *v) const
Current node value at node pointer v.
Definition HLD.H:1124
size_t id_of(const Node *node) const
Map a Node pointer to its internal ID.
Definition HLD.H:824
size_t size() const noexcept
Total number of nodes in the tree.
Definition HLD.H:806
const Array< size_t > & position_array() const noexcept
Read-only access to the flat-position array.
Definition HLD.H:1083
Node * lca(const Node *u, const Node *v) const
LCA query by node pointers in O(log n).
Definition HLD.H:1052
size_t parent_id(const size_t id) const
Parent ID of node id, or NONE if root.
Definition HLD.H:870
Gen_HLD(Gen_HLD &&other)=default
Take the decomposition and the values of another HLD, which is left empty.
Gen_HLD(const GT &g, Node *root, NodeValueFn &&node_value, const T &identity, Op oper=Op(), SA sa=SA())
Construct HLD from graph, root, and node value functor.
Definition HLD.H:677
Gen_HLD & operator=(const Gen_HLD &other)=default
Copy the decomposition and the values of another HLD.
void point_update(const Node *v, const T &new_value)
Point update by node pointer: set value to new_value.
Definition HLD.H:1023
size_t position(const size_t id) const
HLD flat-array position of node id.
Definition HLD.H:830
size_t lca_id(size_t u, size_t v) const
LCA query by node IDs in O(log n).
Definition HLD.H:1033
void ensure_not_empty(const char *where) const
Definition HLD.H:639
size_t root_id() const noexcept
Returns the internal ID of the root node.
Definition HLD.H:815
const Array< size_t > & subtree_size_array() const noexcept
Read-only access to the subtree-size array.
Definition HLD.H:1105
void build_segment_tree(NodeValueFn &&node_value)
Definition HLD.H:646
T subtree_query(const Node *v) const
Subtree query by node pointer in O(log n).
Definition HLD.H:1000
size_t subtree_size_of(const Node *node) const
Subtree size of node.
Definition HLD.H:864
T path_query_edges_id(size_t u, size_t v) const
Edge-weighted path query by node IDs in O(log^2 n).
Definition HLD.H:944
Gen_HLD(const Gen_HLD &other)=default
Copy the decomposition and the values of another HLD.
bool is_empty() const noexcept
Returns true if the tree has no nodes.
Definition HLD.H:809
size_t depth_of(const Node *node) const
Depth of node from root.
Definition HLD.H:851
Gen_Segment_Tree< T, Op > seg_
Definition HLD.H:635
const Array< size_t > & depth_array() const noexcept
Read-only access to the depth array.
Definition HLD.H:1099
size_t n() const noexcept
Definition HLD.H:637
T subtree_query_id(const size_t v) const
Subtree query by node ID in O(log n).
Definition HLD.H:989
const Array< size_t > & parent_array() const noexcept
Read-only access to the parent array.
Definition HLD.H:1111
typename GT::Node Node
Definition HLD.H:626
size_t distance_id(const size_t u, const size_t v) const
Number of edges between two nodes by IDs in O(log n).
Definition HLD.H:1062
Gen_HLD(const GT &g, NodeValueFn &&node_value, const T &identity, Op oper=Op(), SA sa=SA())
Construct with first graph node as root.
Definition HLD.H:689
Node * root() const noexcept
Returns the root node.
Definition HLD.H:812
Node * parent_of(const Node *node) const
Parent of node, or nullptr if root.
Definition HLD.H:877
T get_value_at_id(const size_t id) const
Current node value at HLD position pos in the segment tree.
Definition HLD.H:1117
T path_query_edges(const Node *u, const Node *v) const
Edge-weighted path query by node pointers.
Definition HLD.H:976
const Array< size_t > & chain_head_array() const noexcept
Read-only access to the chain-head array.
Definition HLD.H:1093
Topology topology_
Definition HLD.H:632
Segment tree over an arbitrary associative binary operation.
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
const Array< size_t > & tout() const noexcept
Definition HLD.H:569
Array< Node * > id_to_node_
Definition HLD.H:141
typename GT::Node Node
Definition HLD.H:126
const Array< size_t > & chain_head() const noexcept
Definition HLD.H:567
HLD_Tree_Data & operator=(const HLD_Tree_Data &other)=default
Copy the decomposition of another tree.
void validate_id(const size_t id, const char *where) const
Definition HLD.H:590
const Array< size_t > & parent() const noexcept
Definition HLD.H:563
void swap_filter(HLD_Tree_Data &other) noexcept(std::is_nothrow_swappable_v< SA >)
Exchange the filters of this topology and another, for an owner that exchanges something else before ...
Definition HLD.H:526
void swap_but_filter(HLD_Tree_Data &other) noexcept
Exchange in O(1) all but the filters of this topology and another.
Definition HLD.H:538
const Array< size_t > & tin() const noexcept
Definition HLD.H:568
HLD_Tree_Data(HLD_Tree_Data &&other) noexcept(std::is_nothrow_move_constructible_v< SA >)
Take the decomposition of another tree, which is left empty.
Definition HLD.H:479
HLD_Tree_Data(const GT &g, Node *root, SA sa=SA())
Definition HLD.H:454
const Array< size_t > & subtree_size() const noexcept
Definition HLD.H:565
static Pair_Key normalize_pair(size_t u, size_t v) noexcept
Definition HLD.H:157
Array< size_t > tout_
Definition HLD.H:153
Array< Array< size_t > > adjacency_
Definition HLD.H:144
size_t root_id() const noexcept
Definition HLD.H:560
const Array< Node * > & id_to_node() const noexcept
Definition HLD.H:562
Node * node_of(const size_t id) const
Definition HLD.H:584
Array< size_t > chain_head_
Definition HLD.H:151
Node * root() const noexcept
Definition HLD.H:559
size_t id_of(const Node *node) const
Definition HLD.H:572
static constexpr size_t NONE
Definition HLD.H:129
const Array< size_t > & depth() const noexcept
Definition HLD.H:564
Array< size_t > depth_
Definition HLD.H:146
MapOLhash< Node *, size_t > node_to_id_
Definition HLD.H:142
size_t size() const noexcept
Definition HLD.H:557
size_t num_chains() const noexcept
Definition HLD.H:570
HLD_Tree_Data(const HLD_Tree_Data &other)=default
Copy the decomposition of another tree.
bool is_empty() const noexcept
Definition HLD.H:558
void swap(HLD_Tree_Data &other) noexcept(std::is_nothrow_swappable_v< SA >)
Exchange in O(1) this topology and another.
Definition HLD.H:515
void check_id(const size_t id, const char *where) const
Definition HLD.H:447
Array< size_t > subtree_size_
Definition HLD.H:147
const Array< size_t > & pos() const noexcept
Definition HLD.H:566
Array< size_t > parent_
Definition HLD.H:145
typename GT::Arc Arc
Definition HLD.H:127
std::pair< size_t, size_t > Pair_Key
Definition HLD.H:132
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
STL namespace.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
HLD with path/subtree max queries.
Definition HLD.H:1172
typename GT::Node Node
Definition HLD.H:1174
HLD_Max(const GT &g, Node *root, NodeValueFn &&nv, SA sa=SA())
Definition HLD.H:1177
HLD_Max(const GT &g, NodeValueFn &&nv, SA sa=SA())
Definition HLD.H:1183
HLD with path/subtree min queries.
Definition HLD.H:1199
HLD_Min(const GT &g, Node *root, NodeValueFn &&nv, SA sa=SA())
Definition HLD.H:1204
HLD_Min(const GT &g, NodeValueFn &&nv, SA sa=SA())
Definition HLD.H:1210
typename GT::Node Node
Definition HLD.H:1201
HLD with path/subtree sum queries.
Definition HLD.H:1145
typename GT::Node Node
Definition HLD.H:1147
HLD_Sum(const GT &g, Node *root, NodeValueFn &&nv, SA sa=SA())
Definition HLD.H:1150
HLD_Sum(const GT &g, NodeValueFn &&nv, SA sa=SA())
Definition HLD.H:1156
Open addressing hash map using linear probing.
Data & find(const Key &key)
Find and return the value for a key.
Pair * search(const Key &key) noexcept(nothrow_search< const Key & >)
Search for a key in the map.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair (copy semantics).
Functor returning the maximum of two values.
Functor returning the minimum of two values.
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Dynamic stack implementation based on linked lists.
Dynamic map with open hashing.
Dynamic key-value map based on balanced binary search trees.
Generic graph and digraph implementations.
Segment trees for dynamic range queries with lazy propagation.
DynList< int > l