Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_mo_on_trees.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
89# ifndef TPL_MO_ON_TREES_H
90# define TPL_MO_ON_TREES_H
91
92# include <ah-graph-concepts.H>
93
94# include <algorithm>
95# include <cmath>
96# include <concepts>
97# include <type_traits>
98# include <utility>
99# include <vector>
100# include <tpl_array.H>
101# include <tpl_dynMapOhash.H>
102# include <tpl_dynList.H>
103# include <tpl_dynListStack.H>
104# include <tpl_mo_algorithm.H>
105# include <tpl_sort_utils.H>
106# include <tpl_tree_node.H>
107# include <ah-errors.H>
108
109namespace Aleph
110{
120 template <class GT>
121 concept MoTreeGraph = requires(const GT & g,
122 typename GT::Node * p,
123 typename GT::Arc * a)
124 {
125 typename GT::Node;
126 typename GT::Arc;
127 typename GT::Node::Node_Type;
128 typename GT::Node_Arc_Iterator;
129 { g.vsize() } -> std::convertible_to<size_t>;
130 { g.get_connected_node(a, p) } -> std::same_as<typename GT::Node *>;
131 { typename GT::Node_Arc_Iterator(p) };
132 { g.for_each_node([](typename GT::Node *) {}) };
133 };
134
135 // ================================================================
136 // Gen_Mo_On_Trees
137 // ================================================================
138
170 template <AlephGraph GT, class Policy>
173 {
174 public:
175 using Node = typename GT::Node;
176 using Arc = typename GT::Arc;
177 using T = typename Node::Node_Type;
178 using answer_type = typename Policy::answer_type;
179
180 private:
181 static constexpr size_t NONE = ~static_cast<size_t>(0);
182
183 const GT & g_;
185 mutable Policy pol_;
186 size_t n_ = 0;
187
188 // Node <-> ID mapping (external, zero impact on graph)
192
193 // Single-occurrence Euler tour (for subtree queries, size n)
197
198 // Double-occurrence Euler tour (for path queries, size 2n)
202
203 // Binary lifting for LCA
204 size_t log_n_ = 0;
207 Array<size_t> up_; // flattened [log_n_][n_]: up_(k * n_ + v)
208
209 // ── Build helpers ──────────────────────────────────────────────
210
211 void build()
212 {
213 n_ = g_.vsize();
214 // An empty graph has no node, and so only the null root
215 ah_domain_error_if(n_ == 0 and root_ != nullptr)
216 << "Gen_Mo_On_Trees: root node not found in graph";
217 if (n_ == 0)
218 return;
219
220 // 1. Assign contiguous IDs to nodes (pre-allocate OLhash for n_ entries)
223 {
225 node_to_id_.swap(tmp);
226 }
227
228 {
229 size_t next_id = 0;
230 g_.for_each_node([&](Node * p)
231 {
232 node_to_id_.insert(p, next_id);
233 id_to_node_(next_id) = p;
234 node_values_(next_id) = p->get_info();
235 ++next_id;
236 });
237 }
238
240 << "Gen_Mo_On_Trees: root node not found in graph";
241
242 // 2. Pre-collect adjacency lists as node IDs (Array for O(1) access)
243 auto adj = Array<Array<size_t>>::create(n_);
244 g_.for_each_node([&](Node * p)
245 {
246 const size_t pid = node_to_id_.find(p);
247 DynList<size_t> neighbors;
248 for (auto it = typename GT::Node_Arc_Iterator(p);
249 it.has_curr(); it.next_ne())
250 {
251 auto * a = it.get_curr();
252 auto * neighbor = g_.get_connected_node(a, p);
253 neighbors.append(node_to_id_.find(neighbor));
254 }
255 adj(pid) = Array<size_t>(neighbors);
256 });
257
258 // 3. Iterative DFS to build Euler tours + parent/depth
267 for (size_t i = 0; i < n_; ++i)
268 parent_(i) = NONE;
269
270 auto visited = Array<bool>::create(n_);
271 for (size_t i = 0; i < n_; ++i)
272 visited(i) = false;
273
274 size_t sub_timer = 0;
275 size_t path_timer = 0;
276
277 struct Frame { size_t id; size_t child_idx; };
279
280 const size_t root_id = node_to_id_.find(root_);
281 visited(root_id) = true;
282 depth_(root_id) = 0;
283 parent_(root_id) = NONE;
284
285 tin_(root_id) = sub_timer;
286 flat_sub_(sub_timer) = node_values_(root_id);
287 ++sub_timer;
288
289 first_(root_id) = path_timer;
290 flat_node_(path_timer) = root_id;
291 ++path_timer;
292
293 stk.push({root_id, 0});
294
295 while (not stk.is_empty())
296 {
297 auto & fr = stk.top();
298 bool pushed = false;
299
300 while (fr.child_idx < adj(fr.id).size())
301 {
302 const size_t nid = adj(fr.id)(fr.child_idx++);
303 if (visited(nid))
304 continue;
305
306 visited(nid) = true;
307 parent_(nid) = fr.id;
308 depth_(nid) = depth_(fr.id) + 1;
309
310 tin_(nid) = sub_timer;
311 flat_sub_(sub_timer) = node_values_(nid);
312 ++sub_timer;
313
314 first_(nid) = path_timer;
315 flat_node_(path_timer) = nid;
316 ++path_timer;
317
318 stk.push({nid, 0});
319 pushed = true;
320 break;
321 }
322
323 if (not pushed)
324 {
325 tout_(fr.id) = sub_timer - 1;
326
327 last_(fr.id) = path_timer;
328 flat_node_(path_timer) = fr.id;
329 ++path_timer;
330
331 (void) stk.pop();
332 }
333 }
334
335 ah_domain_error_if(sub_timer != n_)
336 << "Gen_Mo_On_Trees: graph is not connected (not a tree)";
337
338 // 4. Binary lifting table for LCA
339 log_n_ = 1;
340 while ((static_cast<size_t>(1) << log_n_) < n_)
341 ++log_n_;
342 ++log_n_;
343
345 for (size_t i = 0; i < log_n_ * n_; ++i)
346 up_(i) = NONE;
347
348 for (size_t v = 0; v < n_; ++v)
349 up_(0 * n_ + v) = parent_(v);
350
351 for (size_t k = 1; k < log_n_; ++k)
352 for (size_t v = 0; v < n_; ++v)
353 up_(k * n_ + v) = (up_((k-1) * n_ + v) == NONE)
354 ? NONE
355 : up_((k-1) * n_ + up_((k-1) * n_ + v));
356 }
357
358 // LCA via binary lifting – O(log N)
359 size_t lca(size_t u, size_t v) const
360 {
361 if (depth_(u) < depth_(v))
362 std::swap(u, v);
363
364 const size_t diff = depth_(u) - depth_(v);
365 for (size_t k = 0; k < log_n_; ++k)
366 if ((diff >> k) & 1)
367 u = up_(k * n_ + u);
368
369 if (u == v)
370 return u;
371
372 for (int k = static_cast<int>(log_n_) - 1; k >= 0; --k)
373 if (up_(k * n_ + u) != up_(k * n_ + v))
374 {
375 u = up_(k * n_ + u);
376 v = up_(k * n_ + v);
377 }
378
379 return up_(0 * n_ + u);
380 }
381
382 // Standard Mo sweep (used for subtree queries)
384 Array<Mo_Query> queries,
385 size_t n) const
386 {
387 const size_t q = queries.size();
388 const size_t block = std::max<size_t>(
389 1, static_cast<size_t>(std::sqrt(static_cast<double>(n))));
390
391 introsort(queries,
392 [block](const Mo_Query & a, const Mo_Query & b)
393 {
394 const size_t ba = a.l / block;
395 const size_t bb = b.l / block;
396 if (ba != bb)
397 return ba < bb;
398 return (ba & 1) ? (a.r > b.r) : (a.r < b.r);
399 });
400
401 pol_.init(data, n);
402
403 auto answers = Array<answer_type>::create(q);
404
405 size_t cur_l = queries(0).l;
406 size_t cur_r = queries(0).l;
407 pol_.add(data, cur_l);
408
409 while (cur_r < queries(0).r)
410 pol_.add(data, ++cur_r);
411
412 answers(queries(0).id) = pol_.answer();
413
414 for (size_t i = 1; i < q; ++i)
415 {
416 const size_t ql = queries(i).l;
417 const size_t qr = queries(i).r;
418
419 while (cur_r < qr)
420 pol_.add(data, ++cur_r);
421
422 while (cur_l > ql)
423 pol_.add(data, --cur_l);
424
425 while (cur_r > qr)
426 pol_.remove(data, cur_r--);
427
428 while (cur_l < ql)
429 pol_.remove(data, cur_l++);
430
431 answers(queries(i).id) = pol_.answer();
432 }
433
434 return answers;
435 }
436
437 public:
438
456 Gen_Mo_On_Trees(const GT & g, Node * root, Policy p = Policy())
457 : g_(g), root_(root), pol_(std::move(p))
458 {
459 build();
460 }
461
465 Gen_Mo_On_Trees(const Gen_Mo_On_Trees & other) = default;
466
478 noexcept(std::is_nothrow_move_constructible_v<Policy>)
479 : g_(other.g_), root_(std::exchange(other.root_, nullptr)),
480 pol_(std::move(other.pol_)), n_(std::exchange(other.n_, 0)),
481 id_to_node_(std::move(other.id_to_node_)), node_to_id_(std::move(other.node_to_id_)),
482 node_values_(std::move(other.node_values_)), tin_(std::move(other.tin_)),
483 tout_(std::move(other.tout_)), flat_sub_(std::move(other.flat_sub_)),
484 first_(std::move(other.first_)), last_(std::move(other.last_)),
485 flat_node_(std::move(other.flat_node_)), log_n_(std::exchange(other.log_n_, 0)),
486 depth_(std::move(other.depth_)), parent_(std::move(other.parent_)),
487 up_(std::move(other.up_))
488 {}
489
491 [[nodiscard]] size_t size() const noexcept { return n_; }
492
494 [[nodiscard]] bool is_empty() const noexcept { return n_ == 0; }
495
496 // ── Subtree queries ──────────────────────────────────────────
497
517 const Array<Node*> & query_roots) const
518 {
519 const size_t q = query_roots.size();
520 if (q == 0)
521 return Array<answer_type>();
522
523 auto queries = Array<Mo_Query>::create(q);
524 for (size_t i = 0; i < q; ++i)
525 {
526 auto * p = node_to_id_.search(query_roots(i));
527 ah_domain_error_if(p == nullptr)
528 << "subtree_solve: query " << i << " node not in tree";
529 const size_t id = p->second;
530 queries(i) = {tin_(id), tout_(id), i};
531 }
532
533 return mo_sweep(flat_sub_, std::move(queries), n_);
534 }
535
548 std::initializer_list<Node*> il) const
549 {
550 const Array<Node*> roots(il);
551 return subtree_solve(roots);
552 }
553
554 // ── Path queries ─────────────────────────────────────────────
555
577 const Array<std::pair<Node*, Node*>> & query_pairs) const
578 {
579 const size_t q = query_pairs.size();
580 if (q == 0)
581 return Array<answer_type>();
582
583 struct Path_Query
584 {
585 size_t l, r, id, lca_id;
586 };
587
588 auto pqueries = Array<Path_Query>::create(q);
589 for (size_t i = 0; i < q; ++i)
590 {
591 auto * pu = node_to_id_.search(query_pairs(i).first);
592 auto * pv = node_to_id_.search(query_pairs(i).second);
593 ah_domain_error_if(pu == nullptr or pv == nullptr)
594 << "path_solve: query " << i << " node not in tree";
595
596 size_t u = pu->second;
597 size_t v = pv->second;
598
599 if (first_(u) > first_(v))
600 std::swap(u, v);
601
602 if (const size_t ancestor = lca(u, v); ancestor == u)
603 pqueries(i) = {first_(u), first_(v), i, NONE};
604 else
605 pqueries(i) = {last_(u), first_(v), i, ancestor};
606 }
607
608 // Snake sort
609 const size_t tour_sz = 2 * n_;
610 const size_t block = std::max<size_t>(
611 1, static_cast<size_t>(
612 std::sqrt(static_cast<double>(tour_sz))));
613
614 introsort(pqueries,
615 [block](const Path_Query & a, const Path_Query & b)
616 {
617 const size_t ba = a.l / block;
618 const size_t bb = b.l / block;
619 if (ba != bb)
620 return ba < bb;
621 return (ba & 1) ? (a.r > b.r) : (a.r < b.r);
622 });
623
624 pol_.init(node_values_, n_);
625
626 auto answers = Array<answer_type>::create(q);
627 auto active = Array<bool>::create(n_);
628 for (size_t i = 0; i < n_; ++i)
629 active(i) = false;
630
631 // Toggle: flip node activity and call policy add/remove
632 auto toggle = [&](const size_t pos)
633 {
634 if (const size_t nid = flat_node_(pos); active(nid))
635 {
636 pol_.remove(node_values_, nid);
637 active(nid) = false;
638 }
639 else
640 {
641 pol_.add(node_values_, nid);
642 active(nid) = true;
643 }
644 };
645
646 // Initialize window to first query
647 size_t cur_l = pqueries(0).l;
648 size_t cur_r = pqueries(0).l;
649 toggle(cur_l);
650
651 while (cur_r < pqueries(0).r)
652 toggle(++cur_r);
653
654 if (pqueries(0).lca_id != NONE)
655 {
656 pol_.add(node_values_, pqueries(0).lca_id);
657 answers(pqueries(0).id) = pol_.answer();
658 pol_.remove(node_values_, pqueries(0).lca_id);
659 }
660 else
661 answers(pqueries(0).id) = pol_.answer();
662
663 // Sweep remaining queries
664 for (size_t i = 1; i < q; ++i)
665 {
666 const size_t ql = pqueries(i).l;
667 const size_t qr = pqueries(i).r;
668
669 while (cur_r < qr) toggle(++cur_r);
670 while (cur_l > ql) toggle(--cur_l);
671 while (cur_r > qr) toggle(cur_r--);
672 while (cur_l < ql) toggle(cur_l++);
673
674 if (pqueries(i).lca_id != NONE)
675 {
676 pol_.add(node_values_, pqueries(i).lca_id);
677 answers(pqueries(i).id) = pol_.answer();
678 pol_.remove(node_values_, pqueries(i).lca_id);
679 }
680 else
681 answers(pqueries(i).id) = pol_.answer();
682 }
683
684 return answers;
685 }
686
700 std::initializer_list<std::pair<Node*, Node*>> il) const
701 {
702 const Array<std::pair<Node*, Node*>> pairs(il);
703 return path_solve(pairs);
704 }
705 };
706
707 // ================================================================
708 // Gen_Mo_On_Tree_Node — Mo on N-ary trees (Tree_Node<T>)
709 // ================================================================
710
735 template <typename T, class Policy>
736 requires MoPolicy<Policy, T>
738 {
739 public:
741 using answer_type = typename Policy::answer_type;
742
743 private:
744 static constexpr size_t NONE = ~size_t(0);
745
747 mutable Policy pol_;
748 size_t n_ = 0;
749
750 // Node <-> ID mapping
754
755 // Single-occurrence Euler tour (subtree queries, size n)
759
760 // Double-occurrence Euler tour (path queries, size 2n)
764
765 // Binary lifting for LCA
766 size_t log_n_ = 0;
769 Array<size_t> up_; // flattened [log_n_][n_]: up_(k * n_ + v)
770
771 // ── Build ──────────────────────────────────────────────────────
772
773 void build()
774 {
775 // 1. Collect nodes iteratively in preorder (no recursion).
776 n_ = 0;
777 if (root_ == nullptr)
778 return;
779
781 {
783 stk.push(root_);
784
785 while (not stk.is_empty())
786 {
787 Node * curr = stk.pop();
788 preorder.append(curr);
789 ++n_;
790
791 // Push children right-to-left so stack pops left-to-right.
792 DynListStack<Node*> rev_children;
793 for (Node * c = curr->get_left_child(); c != nullptr;
794 c = c->get_right_sibling())
795 rev_children.push(c);
796
797 while (not rev_children.is_empty())
798 stk.push(rev_children.pop());
799 }
800 }
801
802 if (n_ == 0)
803 return;
804
805 // 2. Assign IDs (pre-allocate OLhash for n_ entries)
808 {
810 node_to_id_.swap(tmp);
811 }
812
813 // Pre-collect adjacency as Array<Array<size_t>> for O(1) indexed access
814 auto adj = Array<Array<size_t>>::create(n_);
815 {
816 size_t next_id = 0;
817 for (auto it = preorder.get_it(); it.has_curr(); it.next_ne())
818 {
819 Node * mp = it.get_curr();
820 node_to_id_.insert(mp, next_id);
821 id_to_node_(next_id) = mp;
822 node_values_(next_id) = mp->get_key();
823 ++next_id;
824 }
825
826 // Build adjacency: children plus parent if it belongs to this rooted tree.
827 for (size_t pid = 0; pid < n_; ++pid)
828 {
829 Node * mp = id_to_node_(pid);
830 DynList<size_t> neighbors;
831
832 for (Node * c = mp->get_left_child(); c != nullptr;
833 c = c->get_right_sibling())
834 neighbors.append(node_to_id_.find(c));
835
836 Node * par = mp->get_parent();
837 if (par != nullptr)
838 if (auto * pp = node_to_id_.search(par); pp != nullptr)
839 neighbors.append(pp->second);
840
841 adj(pid) = Array<size_t>(neighbors);
842 }
843 }
844
845 // 3. Iterative DFS for Euler tours + parent/depth
854 for (size_t i = 0; i < n_; ++i)
855 parent_(i) = NONE;
856
857 auto visited = Array<bool>::create(n_);
858 for (size_t i = 0; i < n_; ++i)
859 visited(i) = false;
860
861 size_t sub_timer = 0;
862 size_t path_timer = 0;
863
864 struct Frame { size_t id; size_t child_idx; };
866
867 const size_t root_id = node_to_id_.find(root_);
868 visited(root_id) = true;
869 depth_(root_id) = 0;
870 parent_(root_id) = NONE;
871
872 tin_(root_id) = sub_timer;
873 flat_sub_(sub_timer) = node_values_(root_id);
874 ++sub_timer;
875
876 first_(root_id) = path_timer;
877 flat_node_(path_timer) = root_id;
878 ++path_timer;
879
880 stk.push({root_id, 0});
881
882 while (not stk.is_empty())
883 {
884 auto & fr = stk.top();
885 bool pushed = false;
886
887 while (fr.child_idx < adj(fr.id).size())
888 {
889 const size_t nid = adj(fr.id)(fr.child_idx++);
890 if (visited(nid))
891 continue;
892
893 visited(nid) = true;
894 parent_(nid) = fr.id;
895 depth_(nid) = depth_(fr.id) + 1;
896
897 tin_(nid) = sub_timer;
898 flat_sub_(sub_timer) = node_values_(nid);
899 ++sub_timer;
900
901 first_(nid) = path_timer;
902 flat_node_(path_timer) = nid;
903 ++path_timer;
904
905 stk.push({nid, 0});
906 pushed = true;
907 break;
908 }
909
910 if (not pushed)
911 {
912 tout_(fr.id) = sub_timer - 1;
913
914 last_(fr.id) = path_timer;
915 flat_node_(path_timer) = fr.id;
916 ++path_timer;
917
918 (void) stk.pop();
919 }
920 }
921
922 ah_domain_error_if(sub_timer != n_)
923 << "Gen_Mo_On_Tree_Node: tree traversal inconsistency";
924
925 // 4. Binary lifting table for LCA
926 log_n_ = 1;
927 while ((static_cast<size_t>(1) << log_n_) < n_)
928 ++log_n_;
929 ++log_n_;
930
932 for (size_t i = 0; i < log_n_ * n_; ++i)
933 up_(i) = NONE;
934
935 for (size_t v = 0; v < n_; ++v)
936 up_(0 * n_ + v) = parent_(v);
937
938 for (size_t k = 1; k < log_n_; ++k)
939 for (size_t v = 0; v < n_; ++v)
940 up_(k * n_ + v) = (up_((k-1) * n_ + v) == NONE)
941 ? NONE
942 : up_((k-1) * n_ + up_((k-1) * n_ + v));
943 }
944
945 // LCA via binary lifting – O(log N)
946 size_t lca(size_t u, size_t v) const
947 {
948 if (depth_(u) < depth_(v))
949 std::swap(u, v);
950
951 size_t diff = depth_(u) - depth_(v);
952 for (size_t k = 0; k < log_n_; ++k)
953 if ((diff >> k) & 1)
954 u = up_(k * n_ + u);
955
956 if (u == v)
957 return u;
958
959 for (int k = static_cast<int>(log_n_) - 1; k >= 0; --k)
960 if (up_(k * n_ + u) != up_(k * n_ + v))
961 {
962 u = up_(k * n_ + u);
963 v = up_(k * n_ + v);
964 }
965
966 return up_(0 * n_ + u);
967 }
968
969 // Standard Mo sweep
971 Array<Mo_Query> queries,
972 size_t nn) const
973 {
974 const size_t q = queries.size();
975 const size_t block = std::max<size_t>(
976 1, static_cast<size_t>(std::sqrt(static_cast<double>(nn))));
977
978 introsort(queries,
979 [block](const Mo_Query & a, const Mo_Query & b)
980 {
981 const size_t ba = a.l / block;
982 const size_t bb = b.l / block;
983 if (ba != bb)
984 return ba < bb;
985 return (ba & 1) ? (a.r > b.r) : (a.r < b.r);
986 });
987
988 pol_.init(data, nn);
989
990 auto answers = Array<answer_type>::create(q);
991
992 size_t cur_l = queries(0).l;
993 size_t cur_r = queries(0).l;
994 pol_.add(data, cur_l);
995
996 while (cur_r < queries(0).r)
997 pol_.add(data, ++cur_r);
998
999 answers(queries(0).id) = pol_.answer();
1000
1001 for (size_t i = 1; i < q; ++i)
1002 {
1003 const size_t ql = queries(i).l;
1004 const size_t qr = queries(i).r;
1005
1006 while (cur_r < qr) pol_.add(data, ++cur_r);
1007 while (cur_l > ql) pol_.add(data, --cur_l);
1008 while (cur_r > qr) pol_.remove(data, cur_r--);
1009 while (cur_l < ql) pol_.remove(data, cur_l++);
1010
1011 answers(queries(i).id) = pol_.answer();
1012 }
1013
1014 return answers;
1015 }
1016
1017 public:
1018
1032 Gen_Mo_On_Tree_Node(Node * root, Policy p = Policy())
1033 : root_(root), pol_(std::move(p))
1034 {
1035 ah_domain_error_if(root == nullptr)
1036 << "Gen_Mo_On_Tree_Node: root is null";
1037 build();
1038 }
1039
1044
1059 noexcept(std::is_nothrow_move_constructible_v<Policy>)
1060 : root_(std::exchange(other.root_, nullptr)), pol_(std::move(other.pol_)),
1061 n_(std::exchange(other.n_, 0)), id_to_node_(std::move(other.id_to_node_)),
1062 node_to_id_(std::move(other.node_to_id_)), node_values_(std::move(other.node_values_)),
1063 tin_(std::move(other.tin_)), tout_(std::move(other.tout_)),
1064 flat_sub_(std::move(other.flat_sub_)), first_(std::move(other.first_)),
1065 last_(std::move(other.last_)), flat_node_(std::move(other.flat_node_)),
1066 log_n_(std::exchange(other.log_n_, 0)), depth_(std::move(other.depth_)),
1067 parent_(std::move(other.parent_)), up_(std::move(other.up_))
1068 {}
1069
1075
1082 noexcept(noexcept(swap(other)))
1083 {
1084 swap(other);
1085 return *this;
1086 }
1087
1095 void swap(Gen_Mo_On_Tree_Node & other) noexcept(std::is_nothrow_swappable_v<Policy>)
1096 {
1097 // The swap that the specification evaluates: that of Policy found by
1098 // its arguments, else std::swap(); first when it may throw. When it
1099 // may not, the order cannot be seen, and it goes after the root, as
1100 // it always did: a policy that has state, the default one, would
1101 // reorder the code if it went first
1102 using std::swap;
1103 if constexpr (not std::is_nothrow_swappable_v<Policy>)
1104 swap(pol_, other.pol_);
1105 std::swap(root_, other.root_);
1106 if constexpr (std::is_nothrow_swappable_v<Policy>)
1107 swap(pol_, other.pol_);
1108 std::swap(n_, other.n_);
1109 id_to_node_.swap(other.id_to_node_);
1110 node_to_id_.swap(other.node_to_id_);
1111 node_values_.swap(other.node_values_);
1112 tin_.swap(other.tin_);
1113 tout_.swap(other.tout_);
1114 flat_sub_.swap(other.flat_sub_);
1115 first_.swap(other.first_);
1116 last_.swap(other.last_);
1117 flat_node_.swap(other.flat_node_);
1118 std::swap(log_n_, other.log_n_);
1119 depth_.swap(other.depth_);
1120 parent_.swap(other.parent_);
1121 up_.swap(other.up_);
1122 }
1123
1125 [[nodiscard]] size_t size() const noexcept { return n_; }
1126
1128 [[nodiscard]] bool is_empty() const noexcept { return n_ == 0; }
1129
1130 // ── Subtree queries ──────────────────────────────────────────
1131
1145 const Array<Node*> & query_roots) const
1146 {
1147 const size_t q = query_roots.size();
1148 if (q == 0)
1149 return Array<answer_type>();
1150
1151 auto queries = Array<Mo_Query>::create(q);
1152 for (size_t i = 0; i < q; ++i)
1153 {
1154 auto * p = node_to_id_.search(query_roots(i));
1155 ah_domain_error_if(p == nullptr)
1156 << "subtree_solve: query " << i << " node not in tree";
1157 const size_t id = p->second;
1158 queries(i) = {tin_(id), tout_(id), i};
1159 }
1160
1161 return mo_sweep(flat_sub_, std::move(queries), n_);
1162 }
1163
1176 std::initializer_list<Node*> il) const
1177 {
1178 const Array<Node*> roots(il);
1179 return subtree_solve(roots);
1180 }
1181
1182 // ── Path queries ─────────────────────────────────────────────
1183
1197 const Array<std::pair<Node*, Node*>> & query_pairs) const
1198 {
1199 const size_t q = query_pairs.size();
1200 if (q == 0)
1201 return Array<answer_type>();
1202
1203 struct Path_Query
1204 {
1205 size_t l, r, id, lca_id;
1206 };
1207
1208 auto pqueries = Array<Path_Query>::create(q);
1209 for (size_t i = 0; i < q; ++i)
1210 {
1211 auto * pu = node_to_id_.search(query_pairs(i).first);
1212 auto * pv = node_to_id_.search(query_pairs(i).second);
1213 ah_domain_error_if(pu == nullptr or pv == nullptr)
1214 << "path_solve: query " << i << " node not in tree";
1215
1216 size_t u = pu->second;
1217 size_t v = pv->second;
1218
1219 if (first_(u) > first_(v))
1220 std::swap(u, v);
1221
1222 const size_t ancestor = lca(u, v);
1223
1224 if (ancestor == u)
1225 pqueries(i) = {first_(u), first_(v), i, NONE};
1226 else
1227 pqueries(i) = {last_(u), first_(v), i, ancestor};
1228 }
1229
1230 // Snake sort
1231 const size_t tour_sz = 2 * n_;
1232 const size_t block = std::max<size_t>(
1233 1, static_cast<size_t>(
1234 std::sqrt(static_cast<double>(tour_sz))));
1235
1236 introsort(pqueries,
1237 [block](const Path_Query & a, const Path_Query & b)
1238 {
1239 const size_t ba = a.l / block;
1240 const size_t bb = b.l / block;
1241 if (ba != bb)
1242 return ba < bb;
1243 return (ba & 1) ? (a.r > b.r) : (a.r < b.r);
1244 });
1245
1246 pol_.init(node_values_, n_);
1247
1248 auto answers = Array<answer_type>::create(q);
1249 auto active = Array<bool>::create(n_);
1250 for (size_t i = 0; i < n_; ++i)
1251 active(i) = false;
1252
1253 auto toggle = [&](const size_t pos)
1254 {
1255 if (const size_t nid = flat_node_(pos); active(nid))
1256 {
1257 pol_.remove(node_values_, nid);
1258 active(nid) = false;
1259 }
1260 else
1261 {
1262 pol_.add(node_values_, nid);
1263 active(nid) = true;
1264 }
1265 };
1266
1267 size_t cur_l = pqueries(0).l;
1268 size_t cur_r = pqueries(0).l;
1269 toggle(cur_l);
1270
1271 while (cur_r < pqueries(0).r)
1272 toggle(++cur_r);
1273
1274 if (pqueries(0).lca_id != NONE)
1275 {
1276 pol_.add(node_values_, pqueries(0).lca_id);
1277 answers(pqueries(0).id) = pol_.answer();
1278 pol_.remove(node_values_, pqueries(0).lca_id);
1279 }
1280 else
1281 answers(pqueries(0).id) = pol_.answer();
1282
1283 for (size_t i = 1; i < q; ++i)
1284 {
1285 const size_t ql = pqueries(i).l;
1286 const size_t qr = pqueries(i).r;
1287
1288 while (cur_r < qr) toggle(++cur_r);
1289 while (cur_l > ql) toggle(--cur_l);
1290 while (cur_r > qr) toggle(cur_r--);
1291 while (cur_l < ql) toggle(cur_l++);
1292
1293 if (pqueries(i).lca_id != NONE)
1294 {
1295 pol_.add(node_values_, pqueries(i).lca_id);
1296 answers(pqueries(i).id) = pol_.answer();
1297 pol_.remove(node_values_, pqueries(i).lca_id);
1298 }
1299 else
1300 answers(pqueries(i).id) = pol_.answer();
1301 }
1302
1303 return answers;
1304 }
1305
1319 std::initializer_list<std::pair<Node*, Node*>> il) const
1320 {
1321 const Array<std::pair<Node*, Node*>> pairs(il);
1322 return path_solve(pairs);
1323 }
1324 };
1325
1326 // ================================================================
1327 // Convenient typedefs
1328 // ================================================================
1329
1334 template <class GT>
1338
1343 template <class GT>
1347
1352 template <class GT>
1356
1361 template <typename T>
1364
1369 template <typename T>
1372
1377 template <typename T>
1380
1381} // namespace Aleph
1382
1383# endif // TPL_MO_ON_TREES_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
C++20 concepts for the protocol shared by graph algorithms.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
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
Iterator get_it()
Iterator on the modifiable array, positioned on entry 0.
T & append()
Allocate a new entry to the end of array.
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.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
Offline subtree and path queries on N-ary trees (Tree_Node).
static constexpr size_t NONE
Array< answer_type > path_solve(std::initializer_list< std::pair< Node *, Node * > > il) const
Solve path queries (initializer-list overload).
Gen_Mo_On_Tree_Node(Gen_Mo_On_Tree_Node &&other) noexcept(std::is_nothrow_move_constructible_v< Policy >)
Take the tables of another engine, which is left empty.
size_t size() const noexcept
Number of nodes in the tree.
void swap(Gen_Mo_On_Tree_Node &other) noexcept(std::is_nothrow_swappable_v< Policy >)
Exchange in O(1) this engine and another.
size_t lca(size_t u, size_t v) const
MapOLhash< Node *, size_t > node_to_id_
typename Policy::answer_type answer_type
Gen_Mo_On_Tree_Node & operator=(const Gen_Mo_On_Tree_Node &other)=default
Copy the tables of another engine.
Gen_Mo_On_Tree_Node(const Gen_Mo_On_Tree_Node &other)=default
Copy the tables of another engine.
Array< answer_type > mo_sweep(const Array< T > &data, Array< Mo_Query > queries, size_t nn) const
Array< answer_type > path_solve(const Array< std::pair< Node *, Node * > > &query_pairs) const
Answer path queries on the N-ary tree.
Array< answer_type > subtree_solve(std::initializer_list< Node * > il) const
Solve subtree queries (initializer-list overload).
Array< answer_type > subtree_solve(const Array< Node * > &query_roots) const
Answer subtree queries on the N-ary tree.
Gen_Mo_On_Tree_Node(Node *root, Policy p=Policy())
Construct a Mo's algorithm query engine for N-ary trees.
bool is_empty() const noexcept
True if the tree is empty.
Offline subtree and path queries on trees via Mo's algorithm.
typename Policy::answer_type answer_type
typename Node::Node_Type T
Array< answer_type > path_solve(std::initializer_list< std::pair< Node *, Node * > > il) const
Solve path queries (initializer-list overload).
static constexpr size_t NONE
Array< answer_type > subtree_solve(const Array< Node * > &query_roots) const
Answer subtree queries using Mo's algorithm.
Gen_Mo_On_Trees(Gen_Mo_On_Trees &&other) noexcept(std::is_nothrow_move_constructible_v< Policy >)
Take the tables of another engine, which is left empty, on the same graph.
Array< Node * > id_to_node_
bool is_empty() const noexcept
True if the tree is empty.
Array< size_t > flat_node_
Array< answer_type > subtree_solve(std::initializer_list< Node * > il) const
Answer subtree queries from an initializer list.
Gen_Mo_On_Trees(const Gen_Mo_On_Trees &other)=default
Copy the tables of another engine, on the same graph.
Gen_Mo_On_Trees(const GT &g, Node *root, Policy p=Policy())
Construct a Mo's algorithm query engine for tree queries.
typename GT::Node Node
size_t lca(size_t u, size_t v) const
MapOLhash< Node *, size_t > node_to_id_
size_t size() const noexcept
Number of nodes in the tree.
Array< answer_type > mo_sweep(const Array< T > &data, Array< Mo_Query > queries, size_t n) const
Array< answer_type > path_solve(const Array< std::pair< Node *, Node * > > &query_pairs) const
Answer path queries between node pairs.
typename Node::Node_Type Node_Type
The arc class type.
Definition tpl_graph.H:447
Forward declaration used by CRTP helpers before the full node definition.
Tree_Node * get_left_child() const noexcept
Returns the leftmost child of this.
Tree_Node * get_parent() const noexcept
Returns the parent of this.
T & get_key() noexcept
Returns a modifiable reference to the node contents.
Node * get_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
Definition graph-dry.H:1058
void for_each_node(Operation &operation) const
Unconditionally traverse all the nodes of graph and on each one perform an operation.
Definition graph-dry.H:1765
constexpr size_t vsize() const noexcept
See get_num_nodes().
Definition graph-dry.H:984
Concept constraining a policy for Mo's algorithm.
Concept constraining a graph type usable for Mo on Trees.
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
bool diff(const C1 &c1, const C2 &c2, Eq e=Eq())
Check if two containers differ.
void introsort(T *a, const long l, const long r, const Compare &cmp=Compare())
Sort an array using introsort (introspective sort).
STL namespace.
Policy: count distinct elements in a range.
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).
A query for Mo's algorithm: inclusive range [l, r] with id.
size_t l
Left endpoint (inclusive, 0-based).
size_t r
Right endpoint (inclusive, 0-based).
Policy: "powerful array" sum = sum(cnt[x]^2 * x).
Policy: range mode (most frequent element).
DynArray< int > preorder
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Dynamic stack implementation based on linked lists.
Alias for htlist.H (DynList implementation).
Dynamic map with open hashing.
Mo's algorithm for offline range queries.
Comprehensive sorting algorithms and search utilities for Aleph-w.
General tree (n-ary tree) node.
DynList< int > l