Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_exhaustive_tree_queries_test.cc
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
65#include <algorithm>
66#include <cstddef>
67#include <limits>
68#include <random>
69#include <set>
70#include <stdexcept>
71#include <string>
72#include <tuple>
73#include <type_traits>
74#include <utility>
75#include <vector>
76
77#include <gtest/gtest.h>
78
79#include <tpl_graph.H>
80#include <tpl_tree_node.H>
81#include <LCA.H>
82#include <HLD.H>
83#include <Tree_Decomposition.H>
84#include <Tree_DP.H>
85#include <tpl_mo_on_trees.H>
86
88#include "graph_harness.H"
89#include "graph_oracles.H"
90
91using namespace Aleph;
92using namespace graph_harness;
93namespace oracle = graph_oracles;
95
96namespace
97{
100 constexpr size_t No_Id = std::numeric_limits<size_t>::max();
101
102 std::string text(const std::vector<int> & xs)
103 {
104 std::string r = "{";
105 for (size_t i = 0; i < xs.size(); ++i)
106 r += (i == 0 ? "" : " ") + std::to_string(xs[i]);
107 return r + "}";
108 }
109
111 int floor_log2(size_t n)
112 {
113 int k = 0;
114 while ((size_t(2) << k) <= n)
115 ++k;
116 return k;
117 }
118
122 Spec prufer_tree(int n, const std::vector<int> & seq)
123 {
124 Spec s;
125 s.n = n;
126 if (n < 2)
127 return s;
128 std::vector<int> degree(size_t(n), 1);
129 for (int x : seq)
130 ++degree[size_t(x)];
131 for (int x : seq)
132 for (int leaf = 0; leaf < n; ++leaf)
133 if (degree[size_t(leaf)] == 1)
134 {
135 s.arcs.push_back({leaf, x});
136 --degree[size_t(leaf)];
137 --degree[size_t(x)];
138 break;
139 }
140 std::vector<int> last;
141 for (int x = 0; x < n; ++x)
142 if (degree[size_t(x)] == 1)
143 last.push_back(x);
144 s.arcs.push_back({last[0], last[1]});
145 return s;
146 }
147
150 void shuffle_ends(Spec & s, unsigned key)
151 {
152 std::mt19937 rng(key);
153 for (auto & a : s.arcs)
154 if (rng() % 2 == 1)
155 std::swap(a[0], a[1]);
156 if (rng() % 2 == 1)
157 std::reverse(s.arcs.begin(), s.arcs.end());
158 }
159
163 template <class F>
164 void for_each_tree(int n, size_t step, F && f)
165 {
166 size_t total = 1;
167 for (int i = 0; i < n - 2; ++i)
168 total *= size_t(n);
169 for (size_t k = 0; k < total; k += step)
170 {
171 std::vector<int> seq;
172 size_t c = k;
173 for (int i = 0; i < n - 2; ++i, c /= size_t(n))
174 seq.push_back(int(c % size_t(n)));
175 Spec s = prufer_tree(n, seq);
176 shuffle_ends(s, unsigned(k * 31 + size_t(n)));
177 f(static_cast<const Spec &>(s));
178 }
179 }
180
184 template <class F>
185 void for_each_test_tree(F && f, size_t sparse = 1)
186 {
187 for (int n = 1; n <= 7; ++n)
188 for_each_tree(n, heavy() or n <= 5 ? 1 : sparse * (n == 6 ? 29 : 389), f);
189 }
190
192 Spec random_tree(std::mt19937 & rng, int n)
193 {
194 std::vector<int> seq;
195 for (int i = 0; i < n - 2; ++i)
196 seq.push_back(int(rng() % unsigned(n)));
197 Spec s = prufer_tree(n, seq);
198 shuffle_ends(s, unsigned(rng()));
199 return s;
200 }
201
203 std::vector<int> random_values(std::mt19937 & rng, int n, int lo = -2, int hi = 2)
204 {
205 std::vector<int> v(static_cast<size_t>(n));
206 for (auto & x : v)
207 x = lo + int(rng() % unsigned(hi - lo + 1));
208 return v;
209 }
210
216 enum class Shape { Tree, Near_Tree, Other };
217
218 Shape shape_of(const Spec & s, unsigned long hidden, bool parallel_once = false)
219 {
220 if (s.n == 0)
221 return Shape::Other;
222 std::set<std::pair<int, int>> pairs;
223 for (size_t i = 0; i < s.arcs.size(); ++i)
224 {
225 if (not graph_filters::shown(hidden, int(i)))
226 continue;
227 const int u = std::min(s.arcs[i][0], s.arcs[i][1]);
228 const int v = std::max(s.arcs[i][0], s.arcs[i][1]);
229 if (u == v or (not pairs.insert({u, v}).second and not parallel_once))
230 return Shape::Other;
231 }
232 if (int(pairs.size()) != s.n - 1)
233 return Shape::Other;
234 oracle::Union_Find uf(s.n);
235 for (const auto & [u, v] : pairs)
236 if (not uf.join(u, v))
237 return Shape::Near_Tree;
238 return Shape::Tree;
239 }
240
241 bool is_tree(const Spec & s, unsigned long hidden, bool parallel_once = false)
242 {
243 return shape_of(s, hidden, parallel_once) == Shape::Tree;
244 }
245
249 unsigned long masks_of(const Spec & s)
250 {
251 return s.num_arcs() <= 3 or s.n <= 3 ? 1UL << s.num_arcs() : 1UL;
252 }
253
261 std::vector<int> roots_to_try(const Spec & s, unsigned long hidden, Shape shape)
262 {
263 std::vector<int> r;
264 if (s.n == 0)
265 return {-2, -1};
266 if (shape == Shape::Other)
267 {
268 if (hidden == 0)
269 r.push_back(-1);
270 r.push_back(s.n - 1);
271 return r;
272 }
273 for (int x = -2; x < s.n; ++x)
274 r.push_back(x);
275 return r;
276 }
277
279 bool reaches_all(const Spec & s, int r)
280 {
281 const auto reach = oracle::closure(s, true);
282 for (int x = 0; x < s.n; ++x)
283 if (not oracle::reaches(reach, r, x))
284 return false;
285 return true;
286 }
287
294 struct Rooted_Tree
295 {
296 int n = 0;
297 int root = -1;
298 std::vector<std::vector<int>> adj;
299 std::vector<int> order;
300 std::vector<int> parent;
301 std::vector<int> depth;
302 std::vector<std::vector<int>> children;
303 std::vector<int> size;
304
305 private:
306 mutable std::vector<std::vector<int>> dists;
307 mutable std::vector<std::vector<int>> paths;
308 mutable std::vector<std::vector<int>> subtrees;
309 mutable std::vector<int> lcas;
310
311 public:
312 Rooted_Tree(const Spec & s, int r, unsigned long hidden = 0)
313 : n(s.n), root(r), adj(size_t(s.n)), parent(size_t(s.n), -1),
314 depth(size_t(s.n), 0), children(size_t(s.n)), size(size_t(s.n), 1),
315 paths(size_t(s.n) * size_t(s.n)), subtrees(size_t(s.n)),
316 lcas(size_t(s.n) * size_t(s.n), -1)
317 {
318 for (size_t i = 0; i < s.arcs.size(); ++i)
319 if (graph_filters::shown(hidden, int(i)))
320 {
321 adj[size_t(s.arcs[i][0])].push_back(s.arcs[i][1]);
322 adj[size_t(s.arcs[i][1])].push_back(s.arcs[i][0]);
323 }
324 order = search(r, &parent, &depth);
325 for (int x = 0; x < n; ++x)
326 if (parent[size_t(x)] != -1)
327 children[size_t(parent[size_t(x)])].push_back(x);
328 for (auto it = order.rbegin(); it != order.rend(); ++it)
329 if (parent[size_t(*it)] != -1)
330 size[size_t(parent[size_t(*it)])] += size[size_t(*it)];
331 }
332
335 std::vector<int> search(int x, std::vector<int> * par, std::vector<int> * dep) const
336 {
337 std::vector<bool> seen(size_t(n), false);
338 std::vector<int> queue = {x};
339 seen[size_t(x)] = true;
340 (*dep)[size_t(x)] = 0;
341 for (size_t h = 0; h < queue.size(); ++h)
342 for (int y : adj[size_t(queue[h])])
343 if (not seen[size_t(y)])
344 {
345 seen[size_t(y)] = true;
346 if (par != nullptr)
347 (*par)[size_t(y)] = queue[h];
348 (*dep)[size_t(y)] = (*dep)[size_t(queue[h])] + 1;
349 queue.push_back(y);
350 }
351 return queue;
352 }
353
356 [[nodiscard]] int distance(int u, int v) const
357 {
358 if (dists.empty())
359 for (int x = 0; x < n; ++x)
360 {
361 std::vector<int> d(size_t(n), -1);
362 search(x, nullptr, &d);
363 dists.push_back(d);
364 }
365 return dists[size_t(u)][size_t(v)];
366 }
367
369 [[nodiscard]] bool is_ancestor(int a, int x) const
370 {
371 for (; x != -1; x = parent[size_t(x)])
372 if (x == a)
373 return true;
374 return false;
375 }
376
378 [[nodiscard]] int lca(int u, int v) const
379 {
380 int & a = lcas[size_t(u) * size_t(n) + size_t(v)];
381 if (a == -1)
382 {
383 a = u;
384 while (not is_ancestor(a, v))
385 a = parent[size_t(a)];
386 }
387 return a;
388 }
389
391 [[nodiscard]] const std::vector<int> & path(int u, int v) const
392 {
393 auto & p = paths[size_t(u) * size_t(n) + size_t(v)];
394 if (p.empty())
395 {
396 const int a = lca(u, v);
397 std::vector<int> down;
398 for (int x = u; x != a; x = parent[size_t(x)])
399 p.push_back(x);
400 p.push_back(a);
401 for (int x = v; x != a; x = parent[size_t(x)])
402 down.push_back(x);
403 p.insert(p.end(), down.rbegin(), down.rend());
404 }
405 return p;
406 }
407
409 [[nodiscard]] const std::vector<int> & subtree(int x) const
410 {
411 auto & sub = subtrees[size_t(x)];
412 if (sub.empty())
413 for (int y = 0; y < n; ++y)
414 if (is_ancestor(x, y))
415 sub.push_back(y);
416 return sub;
417 }
418
423 [[nodiscard]] bool by_node(int u, int v) const
424 {
425 return n <= 4 or u == v or u == root or v == root;
426 }
427 };
428
430 Spec from_root(const Spec & s, const Rooted_Tree & t)
431 {
432 Spec r = s;
433 for (auto & a : r.arcs)
434 if (t.parent[size_t(a[0])] == a[1])
435 std::swap(a[0], a[1]);
436 return r;
437 }
438
441 template <class GT>
442 std::vector<std::tuple<int, int, long, void *>> attributes(const Built<GT> & b)
443 {
444 std::vector<std::tuple<int, int, long, void *>> r;
445 auto add = [&r] (auto * x)
446 {
447 int bits = 0;
448 for (int k = 0; k < Num_Bits_Graph; ++k)
449 bits |= int(x->attrs.control_bits.get_bit(k)) << k;
450 r.emplace_back(x->get_info(), bits, x->attrs.counter, x->attrs.cookie);
451 };
452 for (auto * p : b.nodes)
453 add(p);
454 for (auto * a : b.arcs)
455 add(a);
456 return r;
457 }
458
460 template <class E, class F>
461 bool throws(F && f)
462 {
463 try
464 {
465 f();
466 }
467 catch (const E &)
468 {
469 return true;
470 }
471 catch (...)
472 {
473 return false;
474 }
475 return false;
476 }
477
484 template <class GT, class Engine>
485 std::string tree_error(const Built<GT> & b, const Rooted_Tree & t, const Engine & e)
486 {
487 const int n = t.n;
488 if (e.size() != size_t(n))
489 return "the size is " + std::to_string(e.size());
490 if constexpr (requires { e.is_empty(); })
491 if (e.is_empty() != (n == 0))
492 return "is_empty() is wrong";
493
494 std::vector<size_t> id(static_cast<size_t>(n));
495 std::vector<bool> used(size_t(n), false);
496 for (int x = 0; x < n; ++x)
497 {
498 const size_t i = e.id_of(b.nodes[size_t(x)]);
499 if (i >= size_t(n) or used[i] or e.node_of(i) != b.nodes[size_t(x)])
500 return "the ids do not number the nodes";
501 used[i] = true;
502 id[size_t(x)] = i;
503 }
504
505 if constexpr (requires { e.root_id(); })
506 if (e.root() != b.nodes[size_t(t.root)] or e.root_id() != id[size_t(t.root)])
507 return "the root is not " + std::to_string(t.root);
508
509 for (int x = 0; x < n; ++x)
510 {
511 const size_t i = id[size_t(x)];
512 auto * p = b.nodes[size_t(x)];
513 const int y = t.parent[size_t(x)];
514 const std::string of = " of " + std::to_string(x);
515 if constexpr (requires { e.depth_of_id(i); })
516 if (e.depth_of_id(i) != size_t(t.depth[size_t(x)])
517 or e.depth_of(p) != size_t(t.depth[size_t(x)]))
518 return "the depth" + of;
519 if constexpr (requires { e.parent_id(i); })
520 if (e.parent_id(i) != (y == -1 ? No_Id : id[size_t(y)])
521 or e.parent_of(p) != (y == -1 ? nullptr : b.nodes[size_t(y)]))
522 return "the parent" + of;
523 if constexpr (requires { e.subtree_size_of_id(i); })
524 if (e.subtree_size_of_id(i) != size_t(t.size[size_t(x)])
525 or e.subtree_size_of(p) != size_t(t.size[size_t(x)]))
526 return "the subtree size" + of;
527 }
528
529 for (int u = 0; u < n; ++u)
530 for (int v = 0; v < n; ++v)
531 {
532 const size_t i = id[size_t(u)], j = id[size_t(v)];
533 auto * p = b.nodes[size_t(u)];
534 auto * q = b.nodes[size_t(v)];
535 const bool by_node = t.by_node(u, v);
536 auto of = [&] { return " of " + std::to_string(u) + " and " + std::to_string(v); };
537 if constexpr (requires { e.lca_id(i, j); })
538 {
539 const int a = t.lca(u, v);
540 if (e.lca_id(i, j) != id[size_t(a)] or (by_node and e.lca(p, q) != b.nodes[size_t(a)]))
541 return "the lowest common ancestor" + of();
542 }
543 if constexpr (requires { e.distance_id(i, j); })
544 {
545 const size_t d = size_t(t.distance(u, v));
546 if (e.distance_id(i, j) != d or (by_node and e.distance(p, q) != d))
547 return "the distance" + of();
548 }
549 if constexpr (requires { e.is_ancestor_id(i, j); })
550 if (e.is_ancestor_id(i, j) != t.is_ancestor(u, v)
551 or (by_node and e.is_ancestor(p, q) != t.is_ancestor(u, v)))
552 return "the ancestry" + of();
553 }
554 return "";
555 }
556
563 template <class GT, class Make, class Answer>
564 void expect_taken(Check & c, const Spec & s, const Built<GT> & b, unsigned long hidden,
565 Shape shape, int r, Make make, Answer answer)
566 {
567 c.run();
568 const bool tree = shape == Shape::Tree;
569 auto at = [&]
570 {
571 return "hiding " + std::to_string(hidden)
572 + (r < 0 ? ", the first node as the root: " : ", rooted at " + std::to_string(r) + ": ");
573 };
574 try
575 {
576 const auto e = make();
577 if (s.n == 0)
578 {
579 if (e.size() != 0)
580 c.fail(s, at() + "an engine of the empty graph that is not empty");
581 }
582 else if (not tree)
583 c.fail(s, at() + "takes a graph that is not a tree");
584 else
585 {
586 const Rooted_Tree t(s, r < 0 ? num(b.g.get_first_node()) : r, hidden);
587 if (auto err = answer(e, t); not err.empty())
588 c.fail(s, at() + err);
589 }
590 }
591 catch (const std::domain_error &)
592 {
593 if (tree or s.n == 0)
594 c.fail(s, at() + "rejects a tree");
595 }
596 catch (const std::exception & ex)
597 {
598 c.fail(s, at() + "throws " + ex.what());
599 }
600 }
601
603 int value_of(int x) { return x % 5 - 2; }
604
606 template <class GT>
607 std::vector<int> values_of(const Built<GT> & b)
608 {
609 std::vector<int> val;
610 for (size_t x = 0; x < b.nodes.size(); ++x)
611 val.push_back(value_of(int(x)));
612 return val;
613 }
614
631 template <class GT, class Make, class Answer>
632 void expect_takes_the_trees(const std::string & name, bool parallel_once, bool every_mask,
633 Make make, Answer answer)
634 {
635 Check taken(name + ", the graphs it takes");
636 Check foreign(name + ", a root of another graph");
637 Check untouched(name + " leaves the graph as it was");
638 Built<GT> other(Spec{1, {}, {}});
639
640 for_each_spec(domain(4, 3), GT().is_digraph(), [&] (const Spec & s)
641 {
642 Built<GT> b(s);
643 const auto before = attributes(b);
644 for (unsigned long hidden = 0; hidden < masks_of(s); ++hidden)
645 {
646 const Shape shape = shape_of(s, hidden, parallel_once);
647 if (hidden != 0 and shape == Shape::Other and not every_mask)
648 continue;
649 // -2 is the null root, and -1 the constructor without a root
650 for (int r : roots_to_try(s, hidden, shape))
651 expect_taken(taken, s, b, hidden, shape, r, [&]
652 {
653 return make(b, hidden, r < 0 ? nullptr : b.nodes[size_t(r)], r);
654 }, [&] (const auto & e, const Rooted_Tree & t) { return answer(b, e, t); });
655 }
656
657 foreign.run();
658 if (not throws<std::domain_error>([&] { (void) make(b, 0, other.nodes[0], 0); }))
659 foreign.fail(s, "takes a root of another graph");
660
661 untouched.run();
662 if (attributes(b) != before)
663 untouched.fail(s, "the infos, bits, counters or cookies changed");
664 });
665
666 taken.expect();
667 foreign.expect();
668 untouched.expect();
669 }
670}
671
672// --------------------------------------------------------------------------
673// LCA.H
674// --------------------------------------------------------------------------
675
676namespace
677{
681 template <class GT, class LCA>
682 std::string kth_error(const Built<GT> & b, const Rooted_Tree & t, const LCA & lca)
683 {
684 for (int x = 0; x < t.n; ++x)
685 {
686 const size_t i = lca.id_of(b.nodes[size_t(x)]);
687 int a = x;
688 for (int k = 0; k <= t.depth[size_t(x)] + 1; ++k)
689 {
690 const size_t want = a == -1 ? No_Id : lca.id_of(b.nodes[size_t(a)]);
691 if (lca.kth_ancestor_id(i, size_t(k)) != want
692 or lca.kth_ancestor(b.nodes[size_t(x)], size_t(k))
693 != (a == -1 ? nullptr : b.nodes[size_t(a)]))
694 return "the ancestor " + std::to_string(k) + " arcs above " + std::to_string(x);
695 a = a == -1 ? -1 : t.parent[size_t(a)];
696 }
697 if (lca.kth_ancestor_id(i, No_Id) != No_Id)
698 return "an ancestor of " + std::to_string(x) + " far above the root";
699 }
700 return "";
701 }
702
707 template <class LCA>
708 std::string euler_tour_error(const Rooted_Tree & t, const LCA & er)
709 {
710 const auto & tour = er.euler_tour();
711 const size_t len = er.euler_tour_size();
712 if (len != size_t(2 * t.n - 1) or tour.size() != len)
713 return "a tour of " + std::to_string(len) + " steps";
714 std::vector<int> seq;
715 for (size_t i = 0; i < len; ++i)
716 {
717 if (tour[i] >= size_t(t.n))
718 return "a tour through an id out of range";
719 seq.push_back(num(er.node_of(tour[i])));
720 }
721 if (seq[0] != t.root)
722 return "a tour that does not start at the root";
723 std::vector<bool> seen(size_t(t.n), false);
724 seen[size_t(t.root)] = true;
725 int at = t.root;
726 for (size_t i = 1; i < seq.size(); ++i)
727 {
728 const int x = seq[i];
729 const auto & ch = t.children[size_t(at)];
730 const bool done = std::all_of(ch.begin(), ch.end(), [&] (int c) { return seen[size_t(c)]; });
731 if (t.parent[size_t(x)] == at and not seen[size_t(x)])
732 seen[size_t(x)] = true;
733 else if (x != t.parent[size_t(at)] or not done)
734 return "the tour goes from " + std::to_string(at) + " to " + std::to_string(x);
735 at = x;
736 }
737 if (at != t.root or std::find(seen.begin(), seen.end(), false) != seen.end())
738 return "the tour does not end at the root with every node visited";
739 return "";
740 }
741}
742
743template <class GT>
744class ExhaustiveTreeQueries : public ::testing::Test {};
745
747
748TYPED_TEST(ExhaustiveTreeQueries, LcaEnginesAnswerEveryQuery)
749{
750 using GT = TypeParam;
751 using Node = typename GT::Node;
752 Check lifting("Gen_Binary_Lifting_LCA");
753 Check kth("Gen_Binary_Lifting_LCA::kth_ancestor()");
754 Check levels("Gen_Binary_Lifting_LCA::num_levels()");
755 Check euler("Gen_Euler_RMQ_LCA");
756 Check tour("Gen_Euler_RMQ_LCA::euler_tour()");
757 Check first("the LCA engines rooted at the first node");
758
759 for_each_test_tree([&] (const Spec & s)
760 {
761 Built<GT> b(s);
762 for (int r = 0; r < s.n; ++r)
763 {
764 const Rooted_Tree t(s, r);
765 const std::string at = "rooted at " + std::to_string(r) + ": ";
766
767 lifting.run();
768 const Binary_Lifting_LCA<GT> bl(b.g, b.nodes[size_t(r)]);
769 if (auto e = tree_error(b, t, bl); not e.empty())
770 lifting.fail(s, at + e);
771
772 kth.run();
773 if (auto e = kth_error(b, t, bl); not e.empty())
774 kth.fail(s, at + e);
775
776 euler.run();
777 const Euler_RMQ_LCA<GT> er(b.g, b.nodes[size_t(r)]);
778 if (auto e = tree_error(b, t, er); not e.empty())
779 euler.fail(s, at + e);
780
781 tour.run();
782 if (auto e = euler_tour_error(t, er); not e.empty())
783 tour.fail(s, at + e);
784 }
785
786 const Gen_Binary_Lifting_LCA<GT> bl(b.g);
787 const size_t want_levels = size_t(floor_log2(size_t(s.n)) + 1);
788 levels.run();
789 if (bl.num_levels() != want_levels)
790 levels.fail(s, std::to_string(bl.num_levels()) + " levels, not "
791 + std::to_string(want_levels));
792
793 // Without a root, or with the null one, the root is the first node
794 first.run();
795 const Rooted_Tree t(s, num(b.g.get_first_node()));
796 const Gen_Euler_RMQ_LCA<GT> er(b.g);
797 const Gen_Binary_Lifting_LCA<GT> bl_null(b.g, static_cast<Node *>(nullptr));
798 const Gen_Euler_RMQ_LCA<GT> er_null(b.g, static_cast<Node *>(nullptr));
799 for (const auto & e : {tree_error(b, t, bl), tree_error(b, t, er),
800 tree_error(b, t, bl_null), tree_error(b, t, er_null)})
801 if (not e.empty())
802 {
803 first.fail(s, e);
804 break;
805 }
806 });
807
808 lifting.expect();
809 kth.expect();
810 levels.expect();
811 euler.expect();
812 tour.expect();
813 first.expect();
814}
815
816TYPED_TEST(ExhaustiveTreeQueries, BinaryLiftingLcaTakesExactlyTheTrees)
817{
818 using GT = TypeParam;
819 using Filter = Hide_Mask<GT>;
821 expect_takes_the_trees<GT>("Gen_Binary_Lifting_LCA", false, true,
822 [] (const Built<GT> & b, unsigned long hidden, typename GT::Node * root, int r)
823 {
824 return r == -1 ? Engine(b.g, Filter{hidden}) : Engine(b.g, root, Filter{hidden});
825 },
826 [] (const Built<GT> & b, const auto & e, const Rooted_Tree & t) { return tree_error(b, t, e); });
827}
828
829TYPED_TEST(ExhaustiveTreeQueries, EulerRmqLcaTakesExactlyTheTrees)
830{
831 using GT = TypeParam;
832 using Filter = Hide_Mask<GT>;
833 using Engine = Gen_Euler_RMQ_LCA<GT, Filter>;
834 expect_takes_the_trees<GT>("Gen_Euler_RMQ_LCA", false, false,
835 [] (const Built<GT> & b, unsigned long hidden, typename GT::Node * root, int r)
836 {
837 return r == -1 ? Engine(b.g, Filter{hidden}) : Engine(b.g, root, Filter{hidden});
838 },
839 [] (const Built<GT> & b, const auto & e, const Rooted_Tree & t) { return tree_error(b, t, e); });
840}
841
842TYPED_TEST(ExhaustiveTreeQueries, LcaEnginesOnRandomTrees)
843{
844 using GT = TypeParam;
845 Check lifting("Gen_Binary_Lifting_LCA");
846 Check kth("Gen_Binary_Lifting_LCA::kth_ancestor()");
847 Check euler("Gen_Euler_RMQ_LCA");
848 Check tour("Gen_Euler_RMQ_LCA::euler_tour()");
849
850 std::mt19937 rng(seed(7331));
851 const int trees = heavy() ? 300 : 30;
852 for (int k = 0; k < trees; ++k)
853 {
854 const Spec s = random_tree(rng, 8 + int(rng() % 57));
855 Built<GT> b(s);
856 for (int r : {0, s.n - 1, int(rng() % unsigned(s.n))})
857 {
858 const Rooted_Tree t(s, r);
859 const std::string at = "rooted at " + std::to_string(r) + ": ";
860 const Gen_Binary_Lifting_LCA<GT> bl(b.g, b.nodes[size_t(r)]);
861 const Gen_Euler_RMQ_LCA<GT> er(b.g, b.nodes[size_t(r)]);
862
863 lifting.run();
864 if (auto e = tree_error(b, t, bl); not e.empty())
865 lifting.fail(s, at + e);
866 kth.run();
867 if (auto e = kth_error(b, t, bl); not e.empty())
868 kth.fail(s, at + e);
869 euler.run();
870 if (auto e = tree_error(b, t, er); not e.empty())
871 euler.fail(s, at + e);
872 tour.run();
873 if (auto e = euler_tour_error(t, er); not e.empty())
874 tour.fail(s, at + e);
875 }
876 }
877
878 lifting.expect();
879 kth.expect();
880 euler.expect();
881 tour.expect();
882}
883
884// --------------------------------------------------------------------------
885// HLD.H
886// --------------------------------------------------------------------------
887
888namespace
889{
891 struct Summary
892 {
893 long long sum = 0;
894 long long count = 0;
895 int low = std::numeric_limits<int>::max();
896 int high = std::numeric_limits<int>::lowest();
897
898 bool operator == (const Summary &) const = default;
899 };
900
903 struct Summary_Op
904 {
905 Summary operator () (const Summary & a, const Summary & b) const noexcept
906 {
907 return {a.sum + b.sum, a.count + b.count, std::min(a.low, b.low), std::max(a.high, b.high)};
908 }
909 };
910
911 Summary summary_of(int v) { return {v, 1, v, v}; }
912
913 std::vector<Summary> summaries(const std::vector<int> & val)
914 {
915 std::vector<Summary> r;
916 for (int v : val)
917 r.push_back(summary_of(v));
918 return r;
919 }
920
921 std::string show(long long x) { return std::to_string(x); }
922
923 std::string show(const Summary & s)
924 {
925 return "(" + std::to_string(s.sum) + " " + std::to_string(s.count) + " "
926 + std::to_string(s.low) + " " + std::to_string(s.high) + ")";
927 }
928
930 template <typename T, class Op>
931 T fold(const std::vector<int> & nodes, const std::vector<T> & val, const T & identity,
932 Op op, int skip = -1)
933 {
934 T r = identity;
935 for (int x : nodes)
936 if (x != skip)
937 r = op(r, val[size_t(x)]);
938 return r;
939 }
940
947 template <class GT, class HLD, typename T, class Op>
948 std::string fold_error(const Built<GT> & b, const Rooted_Tree & t, const HLD & h,
949 const std::vector<T> & val, const T & identity, Op op,
950 bool by_node = true)
951 {
952 const int n = t.n;
953 std::vector<size_t> id(static_cast<size_t>(n));
954 for (int x = 0; x < n; ++x)
955 id[size_t(x)] = h.id_of(b.nodes[size_t(x)]);
956
957 for (int x = 0; x < n; ++x)
958 {
959 auto * p = b.nodes[size_t(x)];
960 if (h.get_value_at_id(id[size_t(x)]) != val[size_t(x)]
961 or (by_node and h.get_value(p) != val[size_t(x)]))
962 return "the value of " + std::to_string(x);
963 const T want = fold(t.subtree(x), val, identity, op);
964 const T got = h.subtree_query_id(id[size_t(x)]);
965 if (got != want or (by_node and h.subtree_query(p) != want))
966 return "the subtree of " + std::to_string(x) + " gives " + show(got) + ", not "
967 + show(want);
968 }
969
970 for (int u = 0; u < n; ++u)
971 for (int v = 0; v < n; ++v)
972 {
973 const auto & path = t.path(u, v);
974 auto * p = b.nodes[size_t(u)];
975 auto * q = b.nodes[size_t(v)];
976 const bool pair_by_node = by_node and t.by_node(u, v);
977 auto from = [&] { return " from " + std::to_string(u) + " to " + std::to_string(v); };
978 const T want = fold(path, val, identity, op);
979 const T got = h.path_query_id(id[size_t(u)], id[size_t(v)]);
980 if (got != want or (pair_by_node and h.path_query(p, q) != want))
981 return "the path" + from() + " gives " + show(got) + ", not " + show(want);
982 const T want_edges = fold(path, val, identity, op, t.lca(u, v));
983 const T got_edges = h.path_query_edges_id(id[size_t(u)], id[size_t(v)]);
984 if (got_edges != want_edges or (pair_by_node and h.path_query_edges(p, q) != want_edges))
985 return "the arcs of the path" + from() + " give " + show(got_edges) + ", not "
986 + show(want_edges);
987 }
988 return "";
989 }
990
998 std::string layout_error(const Rooted_Tree & t, const std::vector<size_t> & pos,
999 const std::vector<int> & head)
1000 {
1001 const int n = t.n;
1002 std::vector<bool> taken(size_t(n), false);
1003 for (int x = 0; x < n; ++x)
1004 {
1005 if (pos[size_t(x)] >= size_t(n) or taken[pos[size_t(x)]])
1006 return "the places do not number the nodes";
1007 taken[pos[size_t(x)]] = true;
1008 }
1009 for (int x = 0; x < n; ++x)
1010 for (int y = 0; y < n; ++y)
1011 if (t.is_ancestor(x, y) != (pos[size_t(x)] <= pos[size_t(y)]
1012 and pos[size_t(y)] < pos[size_t(x)] + size_t(t.size[size_t(x)])))
1013 return "the subtree of " + std::to_string(x) + " is not its range of places";
1014 if (head[size_t(t.root)] != t.root)
1015 return "the root does not start a chain";
1016 for (int x = 0; x < n; ++x)
1017 {
1018 int going_on = 0;
1019 for (int c : t.children[size_t(x)])
1020 if (head[size_t(c)] == head[size_t(x)])
1021 {
1022 ++going_on;
1023 for (int d : t.children[size_t(x)])
1024 if (t.size[size_t(d)] > t.size[size_t(c)])
1025 return "the chain of " + std::to_string(x) + " goes on to the light child "
1026 + std::to_string(c);
1027 if (pos[size_t(c)] != pos[size_t(x)] + 1)
1028 return "the chain of " + std::to_string(x) + " is not contiguous";
1029 }
1030 else if (head[size_t(c)] != c)
1031 return "the light child " + std::to_string(c) + " does not start a chain";
1032 if (going_on != (t.children[size_t(x)].empty() ? 0 : 1))
1033 return "the chain of " + std::to_string(x) + " goes on to "
1034 + std::to_string(going_on) + " children";
1035 }
1036 for (int x = 0; x < n; ++x)
1037 {
1038 int light = 0;
1039 for (int y = x; y != t.root; y = t.parent[size_t(y)])
1040 light += head[size_t(y)] == y;
1041 if (light > floor_log2(size_t(n)))
1042 return "the path to " + std::to_string(x) + " enters " + std::to_string(light)
1043 + " chains";
1044 }
1045 return "";
1046 }
1047
1052 template <class GT, class HLD>
1053 std::string hld_layout_error(const Built<GT> & b, const Rooted_Tree & t, const HLD & h)
1054 {
1055 const size_t n = size_t(t.n);
1056 if (h.position_array().size() != n or h.chain_head_array().size() != n
1057 or h.depth_array().size() != n or h.subtree_size_array().size() != n
1058 or h.parent_array().size() != n)
1059 return "an array without a place for each node";
1060 std::vector<size_t> pos(n);
1061 std::vector<int> head(n);
1062 size_t heads = 0;
1063 for (int x = 0; x < t.n; ++x)
1064 {
1065 const size_t i = h.id_of(b.nodes[size_t(x)]);
1066 const size_t hd = h.chain_head_id(i);
1067 const int y = t.parent[size_t(x)];
1068 if (hd >= n)
1069 return "the chain of " + std::to_string(x) + " has no head";
1070 pos[size_t(x)] = h.position(i);
1071 head[size_t(x)] = num(h.node_of(hd));
1072 heads += head[size_t(x)] == x;
1073 if (h.position_array()[i] != pos[size_t(x)] or h.chain_head_array()[i] != hd
1074 or h.depth_array()[i] != size_t(t.depth[size_t(x)])
1075 or h.subtree_size_array()[i] != size_t(t.size[size_t(x)])
1076 or h.parent_array()[i] != (y == -1 ? No_Id : h.id_of(b.nodes[size_t(y)])))
1077 return "the arrays are wrong at " + std::to_string(x);
1078 }
1079 if (h.num_chains() != heads)
1080 return std::to_string(h.num_chains()) + " chains, not " + std::to_string(heads);
1081 return layout_error(t, pos, head);
1082 }
1083
1084 struct Plus
1085 {
1086 long long operator () (long long a, long long b) const { return a + b; }
1087 };
1088
1089 struct Greatest
1090 {
1091 long long operator () (long long a, long long b) const { return std::max(a, b); }
1092 };
1093
1094 struct Least
1095 {
1096 long long operator () (long long a, long long b) const { return std::min(a, b); }
1097 };
1098
1099 constexpr int Lowest = std::numeric_limits<int>::lowest();
1100 constexpr int Highest = std::numeric_limits<int>::max();
1101}
1102
1103TYPED_TEST(ExhaustiveTreeQueries, HldFoldsAndLayoutMatchTheTree)
1104{
1105 using GT = TypeParam;
1106 using Node = typename GT::Node;
1107 Check layout("Gen_HLD, the tree and its layout");
1108 Check sum("HLD_Sum");
1109 Check max("HLD_Max");
1110 Check min("HLD_Min");
1111 Check user("Gen_HLD with an operation of the user");
1112 Check first("Gen_HLD rooted at the first node");
1113
1114 std::mt19937 rng(seed(7332));
1115 for_each_test_tree([&] (const Spec & s)
1116 {
1117 Built<GT> b(s);
1118 std::vector<int> val;
1119 std::vector<Summary> sval;
1120 auto nv = [&val] (Node * p) { return val[size_t(num(p))]; };
1121 auto snv = [&sval] (Node * p) { return sval[size_t(num(p))]; };
1122 for (int r = 0; r < s.n; ++r)
1123 {
1124 const Rooted_Tree t(s, r);
1125 val = random_values(rng, s.n);
1126 sval = summaries(val);
1127 const std::string at = "rooted at " + std::to_string(r) + ": ";
1128
1129 const HLD_Sum<GT, int> hs(b.g, b.nodes[size_t(r)], nv);
1130 layout.run();
1131 if (auto e = tree_error(b, t, hs); not e.empty())
1132 layout.fail(s, at + e);
1133 else if (auto e2 = hld_layout_error(b, t, hs); not e2.empty())
1134 layout.fail(s, at + e2);
1135
1136 sum.run();
1137 if (auto e = fold_error(b, t, hs, val, 0, Plus()); not e.empty())
1138 sum.fail(s, at + e);
1139
1140 max.run();
1141 const HLD_Max<GT, int> hx(b.g, b.nodes[size_t(r)], nv);
1142 if (auto e = fold_error(b, t, hx, val, Lowest, Greatest(), false); not e.empty())
1143 max.fail(s, at + e);
1144
1145 min.run();
1146 const HLD_Min<GT, int> hn(b.g, b.nodes[size_t(r)], nv);
1147 if (auto e = fold_error(b, t, hn, val, Highest, Least(), false); not e.empty())
1148 min.fail(s, at + e);
1149
1150 user.run();
1151 const Gen_HLD<GT, Summary, Summary_Op> hu(b.g, b.nodes[size_t(r)], snv, Summary());
1152 if (auto e = fold_error(b, t, hu, sval, Summary(), Summary_Op()); not e.empty())
1153 user.fail(s, at + e);
1154 }
1155
1156 // Without a root, the root is the first node
1157 first.run();
1158 const Rooted_Tree t(s, num(b.g.get_first_node()));
1159 const HLD_Sum<GT, int> hs(b.g, nv);
1160 const HLD_Max<GT, int> hx(b.g, nv);
1161 const HLD_Min<GT, int> hn(b.g, nv);
1162 const Gen_HLD<GT, Summary, Summary_Op> hu(b.g, snv, Summary());
1163 for (const auto & e : {tree_error(b, t, hs), hld_layout_error(b, t, hs),
1164 fold_error(b, t, hs, val, 0, Plus(), false),
1165 fold_error(b, t, hx, val, Lowest, Greatest(), false),
1166 fold_error(b, t, hn, val, Highest, Least(), false),
1167 tree_error(b, t, hu),
1168 fold_error(b, t, hu, sval, Summary(), Summary_Op(), false)})
1169 if (not e.empty())
1170 {
1171 first.fail(s, e);
1172 break;
1173 }
1174 });
1175
1176 layout.expect();
1177 sum.expect();
1178 max.expect();
1179 min.expect();
1180 user.expect();
1181 first.expect();
1182}
1183
1184TYPED_TEST(ExhaustiveTreeQueries, HldFoldsFollowPointUpdates)
1185{
1186 using GT = TypeParam;
1187 using Node = typename GT::Node;
1188 Check sum("HLD_Sum::point_update()");
1189 Check max("HLD_Max::point_update()");
1190 Check min("HLD_Min::point_update()");
1191 Check user("Gen_HLD::point_update() with an operation of the user");
1192
1193 std::mt19937 rng(seed(7333));
1194 for_each_test_tree([&] (const Spec & s)
1195 {
1196 Built<GT> b(s);
1197 for (int r = 0; r < s.n; ++r)
1198 {
1199 const Rooted_Tree t(s, r);
1200 std::vector<int> val = random_values(rng, s.n);
1201 std::vector<Summary> sval = summaries(val);
1202 auto nv = [&val] (Node * p) { return val[size_t(num(p))]; };
1203 auto snv = [&sval] (Node * p) { return sval[size_t(num(p))]; };
1204 HLD_Sum<GT, int> hs(b.g, b.nodes[size_t(r)], nv);
1205 HLD_Max<GT, int> hx(b.g, b.nodes[size_t(r)], nv);
1206 HLD_Min<GT, int> hn(b.g, b.nodes[size_t(r)], nv);
1207 Gen_HLD<GT, Summary, Summary_Op> hu(b.g, b.nodes[size_t(r)], snv, Summary());
1208
1209 // Two updates, the first by node and the second by id
1210 for (int k = 0; k < 2; ++k)
1211 {
1212 const int x = int(rng() % unsigned(s.n));
1213 const int v = int(rng() % 9) - 4;
1214 auto * p = b.nodes[size_t(x)];
1215 val[size_t(x)] = v;
1216 sval[size_t(x)] = summary_of(v);
1217 if (k == 0)
1218 {
1219 hs.point_update(p, v);
1220 hx.point_update(p, v);
1221 hn.point_update(p, v);
1222 hu.point_update(p, summary_of(v));
1223 }
1224 else
1225 {
1226 hs.point_update_id(hs.id_of(p), v);
1227 hx.point_update_id(hx.id_of(p), v);
1228 hn.point_update_id(hn.id_of(p), v);
1229 hu.point_update_id(hu.id_of(p), summary_of(v));
1230 }
1231 const std::string at = "rooted at " + std::to_string(r) + ", " + std::to_string(x)
1232 + " set to " + std::to_string(v) + ": ";
1233
1234 sum.run();
1235 if (auto e = fold_error(b, t, hs, val, 0, Plus(), false); not e.empty())
1236 sum.fail(s, at + e);
1237 max.run();
1238 if (auto e = fold_error(b, t, hx, val, Lowest, Greatest(), false); not e.empty())
1239 max.fail(s, at + e);
1240 min.run();
1241 if (auto e = fold_error(b, t, hn, val, Highest, Least(), false); not e.empty())
1242 min.fail(s, at + e);
1243 user.run();
1244 if (auto e = fold_error(b, t, hu, sval, Summary(), Summary_Op(), false); not e.empty())
1245 user.fail(s, at + e);
1246 }
1247 }
1248 }, 2);
1249
1250 sum.expect();
1251 max.expect();
1252 min.expect();
1253 user.expect();
1254}
1255
1256TYPED_TEST(ExhaustiveTreeQueries, HldSumTakesExactlyTheTrees)
1257{
1258 using GT = TypeParam;
1259 using Node = typename GT::Node;
1260 using Filter = Hide_Mask<GT>;
1261 using Engine = HLD_Sum<GT, int, Filter>;
1262 auto nv = [] (Node * p) { return value_of(num(p)); };
1263 expect_takes_the_trees<GT>("HLD_Sum", false, true,
1264 [&nv] (const Built<GT> & b, unsigned long hidden, Node * root, int r)
1265 {
1266 return r == -1 ? Engine(b.g, nv, Filter{hidden}) : Engine(b.g, root, nv, Filter{hidden});
1267 },
1268 [] (const Built<GT> & b, const auto & e, const Rooted_Tree & t)
1269 {
1270 if (auto err = tree_error(b, t, e); not err.empty())
1271 return err;
1272 return fold_error(b, t, e, values_of(b), 0, Plus(), false);
1273 });
1274}
1275
1276TYPED_TEST(ExhaustiveTreeQueries, HldWithAnOperationOfTheUserTakesExactlyTheTrees)
1277{
1278 using GT = TypeParam;
1279 using Node = typename GT::Node;
1280 using Filter = Hide_Mask<GT>;
1282 auto nv = [] (Node * p) { return summary_of(value_of(num(p))); };
1283 expect_takes_the_trees<GT>("Gen_HLD with an operation of the user", false, false,
1284 [&nv] (const Built<GT> & b, unsigned long hidden, Node * root, int r)
1285 {
1286 return r == -1 ? Engine(b.g, nv, Summary(), Summary_Op(), Filter{hidden})
1287 : Engine(b.g, root, nv, Summary(), Summary_Op(), Filter{hidden});
1288 },
1289 [] (const Built<GT> & b, const auto & e, const Rooted_Tree & t)
1290 {
1291 if (auto err = hld_layout_error(b, t, e); not err.empty())
1292 return err;
1293 return fold_error(b, t, e, summaries(values_of(b)), Summary(), Summary_Op(), false);
1294 });
1295}
1296
1298{
1299 using GT = TypeParam;
1300 using Node = typename GT::Node;
1301 Check layout("Gen_HLD, the tree and its layout");
1302 Check sum("HLD_Sum, with point updates");
1303 Check user("Gen_HLD with an operation of the user, with point updates");
1304
1305 std::mt19937 rng(seed(7334));
1306 const int trees = heavy() ? 200 : 20;
1307 for (int k = 0; k < trees; ++k)
1308 {
1309 const Spec s = random_tree(rng, 8 + int(rng() % 41));
1310 Built<GT> b(s);
1311 const int r = int(rng() % unsigned(s.n));
1312 const Rooted_Tree t(s, r);
1313 std::vector<int> val = random_values(rng, s.n, -50, 50);
1314 std::vector<Summary> sval = summaries(val);
1315 auto nv = [&val] (Node * p) { return val[size_t(num(p))]; };
1316 auto snv = [&sval] (Node * p) { return sval[size_t(num(p))]; };
1317 HLD_Sum<GT, int> hs(b.g, b.nodes[size_t(r)], nv);
1318 Gen_HLD<GT, Summary, Summary_Op> hu(b.g, b.nodes[size_t(r)], snv, Summary());
1319 const std::string at = "rooted at " + std::to_string(r) + ": ";
1320
1321 layout.run();
1322 if (auto e = tree_error(b, t, hs); not e.empty())
1323 layout.fail(s, at + e);
1324 else if (auto e2 = hld_layout_error(b, t, hs); not e2.empty())
1325 layout.fail(s, at + e2);
1326
1327 for (int u = 0; u < 3; ++u)
1328 {
1329 sum.run();
1330 if (auto e = fold_error(b, t, hs, val, 0, Plus(), u == 0); not e.empty())
1331 sum.fail(s, at + e);
1332 user.run();
1333 if (auto e = fold_error(b, t, hu, sval, Summary(), Summary_Op(), u == 0); not e.empty())
1334 user.fail(s, at + e);
1335 const int x = int(rng() % unsigned(s.n));
1336 val[size_t(x)] = int(rng() % 101) - 50;
1337 sval[size_t(x)] = summary_of(val[size_t(x)]);
1338 hs.point_update(b.nodes[size_t(x)], val[size_t(x)]);
1339 hu.point_update_id(hu.id_of(b.nodes[size_t(x)]), sval[size_t(x)]);
1340 }
1341 }
1342
1343 layout.expect();
1344 sum.expect();
1345 user.expect();
1346}
1347
1348// --------------------------------------------------------------------------
1349// Tree_Decomposition.H
1350// --------------------------------------------------------------------------
1351
1352namespace
1353{
1361 template <class GT, class HLD>
1362 std::string decomposition_error(const Built<GT> & b, const Rooted_Tree & t, const HLD & h)
1363 {
1364 const int n = t.n;
1365 std::vector<size_t> id(static_cast<size_t>(n)), pos(static_cast<size_t>(n));
1366 std::vector<int> head(static_cast<size_t>(n)), at(size_t(n), -1);
1367 for (int x = 0; x < n; ++x)
1368 {
1369 auto * p = b.nodes[size_t(x)];
1370 id[size_t(x)] = h.id_of(p);
1371 pos[size_t(x)] = h.position_of_id(id[size_t(x)]);
1372 if (pos[size_t(x)] >= size_t(n) or h.position_of(p) != pos[size_t(x)])
1373 return "the place of " + std::to_string(x);
1374 at[pos[size_t(x)]] = x;
1375 const size_t hd = h.head_id(id[size_t(x)]);
1376 if (hd >= size_t(n) or h.head_of(p) != h.node_of(hd))
1377 return "the head of the chain of " + std::to_string(x);
1378 head[size_t(x)] = num(h.node_of(hd));
1379 }
1380 if (auto e = layout_error(t, pos, head); not e.empty())
1381 return e;
1382
1383 for (int x = 0; x < n; ++x)
1384 {
1385 auto * p = b.nodes[size_t(x)];
1386 int going_on = -1;
1387 for (int c : t.children[size_t(x)])
1388 if (head[size_t(c)] == head[size_t(x)])
1389 going_on = c;
1390 if (h.heavy_child_id(id[size_t(x)]) != (going_on == -1 ? No_Id : id[size_t(going_on)])
1391 or h.heavy_child(p) != (going_on == -1 ? nullptr : b.nodes[size_t(going_on)]))
1392 return "the heavy child of " + std::to_string(x);
1393 const auto range = h.subtree_range_id(id[size_t(x)]);
1394 const auto by_node = h.subtree_range(p);
1395 if (range.left != pos[size_t(x)] or range.right != pos[size_t(x)] + size_t(t.size[size_t(x)]) - 1
1396 or by_node.left != range.left or by_node.right != range.right)
1397 return "the range of the subtree of " + std::to_string(x);
1398 }
1399
1400 for (int u = 0; u < n; ++u)
1401 for (int v = 0; v < n; ++v)
1402 {
1403 std::vector<int> walk, walk_by_node, covered;
1404 bool bad = false;
1405 auto reader = [&] (std::vector<int> & out)
1406 {
1407 return [&bad, &out, &at, n] (size_t l, size_t r, bool reversed)
1408 {
1409 if (l > r or r >= size_t(n))
1410 {
1411 bad = true;
1412 return;
1413 }
1414 if (reversed)
1415 for (size_t k = r + 1; k-- > l; )
1416 out.push_back(at[k]);
1417 else
1418 for (size_t k = l; k <= r; ++k)
1419 out.push_back(at[k]);
1420 };
1421 };
1422 h.for_each_path_segment_id(id[size_t(u)], id[size_t(v)], reader(walk));
1423 if (t.by_node(u, v))
1424 h.for_each_path_segment(b.nodes[size_t(u)], b.nodes[size_t(v)], reader(walk_by_node));
1425 else
1426 walk_by_node = t.path(u, v);
1427 h.for_each_path_segment_undirected_id(id[size_t(u)], id[size_t(v)],
1428 [&] (size_t l, size_t r)
1429 {
1430 reader(covered)(l, r, false);
1431 });
1432 auto path = t.path(u, v);
1433 auto from = [&] { return " from " + std::to_string(u) + " to " + std::to_string(v); };
1434 if (bad or walk != path or walk_by_node != path)
1435 return "the segments of the path" + from() + " give " + text(walk);
1436 std::sort(path.begin(), path.end());
1437 std::sort(covered.begin(), covered.end());
1438 if (covered != path)
1439 return "the segments without direction of the path" + from() + " cover "
1440 + text(covered);
1441 }
1442 return "";
1443 }
1444
1451 template <class GT, class Query, typename T, class Op>
1452 std::string path_query_error(const Built<GT> & b, const Rooted_Tree & t, const Query & q,
1453 const std::vector<T> & val, const T & identity, Op op,
1454 bool by_node = true)
1455 {
1456 const int n = t.n;
1457 if (q.size() != size_t(n) or q.is_empty() != (n == 0))
1458 return "the size is " + std::to_string(q.size());
1459 if (by_node)
1460 if (auto e = tree_error(b, t, q.decomposition()); not e.empty())
1461 return "decomposition(): " + e;
1462 const auto & h = q.decomposition();
1463 std::vector<size_t> id(static_cast<size_t>(n));
1464 for (int x = 0; x < n; ++x)
1465 id[size_t(x)] = h.id_of(b.nodes[size_t(x)]);
1466 for (int x = 0; x < n; ++x)
1467 {
1468 auto * p = b.nodes[size_t(x)];
1469 const size_t i = id[size_t(x)];
1470 if (q.get_node_id(i) != val[size_t(x)] or (by_node and q.get_node(p) != val[size_t(x)]))
1471 return "the value of " + std::to_string(x);
1472 const T want = fold(t.subtree(x), val, identity, op);
1473 const T got = q.query_subtree_id(i);
1474 if (got != want or (by_node and q.query_subtree(p) != want))
1475 return "the subtree of " + std::to_string(x) + " gives " + show(got) + ", not "
1476 + show(want);
1477 }
1478 for (int u = 0; u < n; ++u)
1479 for (int v = 0; v < n; ++v)
1480 {
1481 auto * p = b.nodes[size_t(u)];
1482 auto * pv = b.nodes[size_t(v)];
1483 const T want = fold(t.path(u, v), val, identity, op);
1484 const T got = q.query_path_id(id[size_t(u)], id[size_t(v)]);
1485 if (got != want or (by_node and t.by_node(u, v) and q.query_path(p, pv) != want))
1486 return "the path from " + std::to_string(u) + " to " + std::to_string(v) + " gives "
1487 + show(got) + ", not " + show(want);
1488 }
1489 return "";
1490 }
1491
1501 template <class GT, class Centroids>
1502 std::string centroid_error(const Built<GT> & b, const Rooted_Tree & t, const Centroids & cd)
1503 {
1504 const int n = t.n;
1505 std::vector<size_t> id(static_cast<size_t>(n));
1506 for (int x = 0; x < n; ++x)
1507 id[size_t(x)] = cd.id_of(b.nodes[size_t(x)]);
1508 auto * top = cd.centroid_root();
1509 if (top == nullptr or cd.centroid_root_id() != cd.id_of(top))
1510 return "the root of the centroid tree";
1511
1512 std::vector<std::vector<int>> chain(static_cast<size_t>(n));
1513 for (int x = 0; x < n; ++x)
1514 {
1515 auto * p = b.nodes[size_t(x)];
1516 const size_t i = id[size_t(x)];
1517 const std::string of = " of " + std::to_string(x);
1518 const auto & anc = cd.centroid_ancestors_of_id(i);
1519 const auto & dist = cd.centroid_distances_of_id(i);
1520 if (&cd.centroid_ancestors_of(p) != &anc or &cd.centroid_distances_of(p) != &dist)
1521 return "the chain" + of + " by node";
1522 if (anc.size() == 0 or anc.size() != dist.size())
1523 return "the chain" + of + " and its distances";
1524 for (size_t k = 0; k < anc.size(); ++k)
1525 {
1526 if (anc[k] >= size_t(n))
1527 return "a centroid ancestor" + of + " out of range";
1528 const int c = num(cd.node_of(anc[k]));
1529 chain[size_t(x)].push_back(c);
1530 if (dist[k] != size_t(t.distance(x, c)))
1531 return "the distance" + of + " to its centroid ancestor " + std::to_string(c);
1532 }
1533 if (chain[size_t(x)].back() != x or chain[size_t(x)].front() != num(top))
1534 return "the chain" + of + " is " + text(chain[size_t(x)]);
1535
1536 std::vector<std::tuple<size_t, size_t, size_t>> seen, seen_by_node;
1537 cd.for_each_centroid_ancestor_id(i, [&] (size_t c, size_t d, size_t k)
1538 {
1539 seen.emplace_back(c, d, k);
1540 });
1541 cd.for_each_centroid_ancestor(p, [&] (size_t c, size_t d, size_t k)
1542 {
1543 seen_by_node.emplace_back(c, d, k);
1544 });
1545 bool same = seen.size() == anc.size() and seen == seen_by_node;
1546 for (size_t k = 0; same and k < seen.size(); ++k)
1547 same = seen[k] == std::make_tuple(anc[k], dist[k], k);
1548 if (not same)
1549 return "for_each_centroid_ancestor()" + of;
1550
1551 const size_t len = chain[size_t(x)].size();
1552 const size_t parent = len == 1 ? No_Id : id[size_t(chain[size_t(x)][len - 2])];
1553 if (cd.centroid_parent_id(i) != parent
1554 or cd.centroid_parent(p) != (len == 1 ? nullptr : cd.node_of(parent))
1555 or cd.centroid_level_of_id(i) != len - 1 or cd.centroid_level_of(p) != len - 1
1556 or cd.centroid_path_length_of_id(i) != len or cd.centroid_path_length_of(p) != len)
1557 return "the parent, the level or the chain length" + of;
1558 }
1559
1560 size_t deepest = 0;
1561 for (int c = 0; c < n; ++c)
1562 {
1563 const auto & ch = chain[size_t(c)];
1564 deepest = std::max(deepest, ch.size() - 1);
1565 if (ch.size() > 1 and std::vector<int>(ch.begin(), ch.end() - 1) != chain[size_t(ch[ch.size() - 2])])
1566 return "the chain of " + std::to_string(c) + " does not extend that of its parent";
1567
1568 // The part of c, and the component of c without its ancestors
1569 std::vector<bool> part(size_t(n), false), out(size_t(n), false), reached(size_t(n), false);
1570 for (int x = 0; x < n; ++x)
1571 part[size_t(x)] = std::find(chain[size_t(x)].begin(), chain[size_t(x)].end(), c)
1572 != chain[size_t(x)].end();
1573 for (size_t k = 0; k + 1 < ch.size(); ++k)
1574 out[size_t(ch[k])] = true;
1575 std::vector<int> todo = {c};
1576 reached[size_t(c)] = true;
1577 while (not todo.empty())
1578 {
1579 const int x = todo.back();
1580 todo.pop_back();
1581 for (int y : t.adj[size_t(x)])
1582 if (not out[size_t(y)] and not reached[size_t(y)])
1583 {
1584 reached[size_t(y)] = true;
1585 todo.push_back(y);
1586 }
1587 }
1588 if (reached != part)
1589 return "the part of the centroid " + std::to_string(c)
1590 + " is not its component without its ancestors";
1591
1592 const auto size = std::count(part.begin(), part.end(), true);
1593 std::vector<bool> taken(size_t(n), false);
1594 for (int y : t.adj[size_t(c)])
1595 if (part[size_t(y)] and not taken[size_t(y)])
1596 {
1597 long count = 0;
1598 std::vector<int> comp = {y};
1599 taken[size_t(y)] = true;
1600 while (not comp.empty())
1601 {
1602 const int x = comp.back();
1603 comp.pop_back();
1604 ++count;
1605 for (int z : t.adj[size_t(x)])
1606 if (part[size_t(z)] and z != c and not taken[size_t(z)])
1607 {
1608 taken[size_t(z)] = true;
1609 comp.push_back(z);
1610 }
1611 }
1612 if (2 * count > size)
1613 return std::to_string(c) + " is not a centroid of its part";
1614 }
1615 }
1616 if (cd.max_centroid_level() != deepest or int(deepest) > floor_log2(size_t(n)))
1617 return "max_centroid_level() is " + std::to_string(cd.max_centroid_level()) + ", not "
1618 + std::to_string(deepest);
1619
1620 for (int a = 0; a < n; ++a)
1621 for (int x = 0; x < n; ++x)
1622 {
1623 const bool in = std::find(chain[size_t(x)].begin(), chain[size_t(x)].end(), a)
1624 != chain[size_t(x)].end();
1625 if (cd.is_centroid_ancestor_id(id[size_t(a)], id[size_t(x)]) != in
1626 or cd.distance_to_centroid_id(id[size_t(x)], id[size_t(a)])
1627 != (in ? size_t(t.distance(x, a)) : No_Id))
1628 return "whether " + std::to_string(a) + " is a centroid ancestor of "
1629 + std::to_string(x) + ", or how far";
1630 }
1631 return "";
1632 }
1633}
1634
1635TYPED_TEST(ExhaustiveTreeQueries, HeavyLightDecompositionMatchesItsDefinition)
1636{
1637 using GT = TypeParam;
1638 Check hld("Gen_Heavy_Light_Decomposition");
1639 Check first("Gen_Heavy_Light_Decomposition rooted at the first node");
1640
1641 for_each_test_tree([&] (const Spec & s)
1642 {
1643 Built<GT> b(s);
1644 for (int r = 0; r < s.n; ++r)
1645 {
1646 const Rooted_Tree t(s, r);
1647 hld.run();
1648 const Heavy_Light_Decomposition<GT> h(b.g, b.nodes[size_t(r)]);
1649 if (auto e = tree_error(b, t, h); not e.empty())
1650 hld.fail(s, "rooted at " + std::to_string(r) + ": " + e);
1651 else if (auto e2 = decomposition_error(b, t, h); not e2.empty())
1652 hld.fail(s, "rooted at " + std::to_string(r) + ": " + e2);
1653 }
1654
1655 first.run();
1656 const Rooted_Tree t(s, num(b.g.get_first_node()));
1658 const Gen_Heavy_Light_Decomposition<GT> h_null(b.g, static_cast<typename GT::Node *>(nullptr));
1659 for (const auto & e : {tree_error(b, t, h), decomposition_error(b, t, h),
1660 tree_error(b, t, h_null)})
1661 if (not e.empty())
1662 {
1663 first.fail(s, e);
1664 break;
1665 }
1666 });
1667
1668 hld.expect();
1669 first.expect();
1670}
1671
1672TYPED_TEST(ExhaustiveTreeQueries, HldPathQueriesFoldAndFollowUpdates)
1673{
1674 using GT = TypeParam;
1675 using Node = typename GT::Node;
1676 Check info("Gen_HLD_Path_Query of the infos");
1677 Check getter("Gen_HLD_Path_Query with a getter");
1678 Check max("Gen_HLD_Path_Query with Max_Op");
1679 Check min("Gen_HLD_Path_Query with Min_Op");
1680 Check user("Gen_HLD_Path_Query with an operation of the user");
1681 Check first("Gen_HLD_Path_Query rooted at the first node");
1682 Check update("Gen_HLD_Path_Query::update_node()");
1683 Check set("Gen_HLD_Path_Query::set_node()");
1684
1685 std::mt19937 rng(seed(7335));
1686 for_each_test_tree([&] (const Spec & s)
1687 {
1688 Built<GT> b(s);
1689 std::vector<int> numbers(size_t(s.n));
1690 for (int x = 0; x < s.n; ++x)
1691 numbers[size_t(x)] = x;
1692 for (int r = 0; r < s.n; ++r)
1693 {
1694 const Rooted_Tree t(s, r);
1695 std::vector<int> val = random_values(rng, s.n);
1696 std::vector<Summary> sval = summaries(val);
1697 auto nv = [&val] (Node * p) { return val[size_t(num(p))]; };
1698 auto snv = [&sval] (Node * p) { return sval[size_t(num(p))]; };
1699 auto * root = b.nodes[size_t(r)];
1700 const std::string at = "rooted at " + std::to_string(r) + ": ";
1701
1702 // The values are the infos, the numbers of the nodes
1703 info.run();
1704 const HLD_Path_Query<GT> qi(b.g, root, 0);
1705 if (auto e = path_query_error(b, t, qi, numbers, 0, Plus(), false); not e.empty())
1706 info.fail(s, at + e);
1707
1708 getter.run();
1709 HLD_Path_Query<GT> q(b.g, root, nv, 0);
1710 if (auto e = path_query_error(b, t, q, val, 0, Plus()); not e.empty())
1711 getter.fail(s, at + e);
1712
1713 max.run();
1714 const HLD_Path_Query<GT, int, Max_Op<int>> qx(b.g, root, nv, Lowest);
1715 if (auto e = path_query_error(b, t, qx, val, Lowest, Greatest(), false); not e.empty())
1716 max.fail(s, at + e);
1717
1718 min.run();
1719 const HLD_Path_Query<GT, int, Min_Op<int>> qn(b.g, root, nv, Highest);
1720 if (auto e = path_query_error(b, t, qn, val, Highest, Least(), false); not e.empty())
1721 min.fail(s, at + e);
1722
1723 user.run();
1724 Gen_HLD_Path_Query<GT, Summary, Summary_Op> qu(b.g, root, snv, Summary());
1725 if (auto e = path_query_error(b, t, qu, sval, Summary(), Summary_Op()); not e.empty())
1726 user.fail(s, at + e);
1727
1728 // An update adds to the value, by node and by id; a set replaces it
1729 const int x = int(rng() % unsigned(s.n));
1730 const int delta = int(rng() % 5) - 2;
1731 update.run();
1732 q.update_node(b.nodes[size_t(x)], delta);
1733 qu.update_node_id(qu.decomposition().id_of(b.nodes[size_t(x)]), summary_of(delta));
1734 val[size_t(x)] += delta;
1735 sval[size_t(x)] = Summary_Op()(sval[size_t(x)], summary_of(delta));
1736 if (auto e = path_query_error(b, t, q, val, 0, Plus(), false); not e.empty())
1737 update.fail(s, at + "adding " + std::to_string(delta) + " to " + std::to_string(x)
1738 + ": " + e);
1739 else if (auto e2 = path_query_error(b, t, qu, sval, Summary(), Summary_Op(), false); not e2.empty())
1740 update.fail(s, at + "adding to " + std::to_string(x) + ": " + e2);
1741
1742 const int y = int(rng() % unsigned(s.n));
1743 const int v = int(rng() % 5) - 2;
1744 set.run();
1745 q.set_node_id(q.decomposition().id_of(b.nodes[size_t(y)]), v);
1746 qu.set_node(b.nodes[size_t(y)], summary_of(v));
1747 val[size_t(y)] = v;
1748 sval[size_t(y)] = summary_of(v);
1749 if (auto e = path_query_error(b, t, q, val, 0, Plus(), false); not e.empty())
1750 set.fail(s, at + "setting " + std::to_string(y) + " to " + std::to_string(v) + ": " + e);
1751 else if (auto e2 = path_query_error(b, t, qu, sval, Summary(), Summary_Op(), false); not e2.empty())
1752 set.fail(s, at + "setting " + std::to_string(y) + ": " + e2);
1753 }
1754
1755 // Without a root, the root is the first node
1756 first.run();
1757 const Rooted_Tree t(s, num(b.g.get_first_node()));
1758 std::vector<int> val = random_values(rng, s.n);
1759 auto nv = [&val] (Node * p) { return val[size_t(num(p))]; };
1760 const HLD_Path_Query<GT> qi(b.g, 0);
1761 const HLD_Path_Query<GT> q(b.g, nv, 0);
1762 for (const auto & e : {path_query_error(b, t, qi, numbers, 0, Plus()),
1763 path_query_error(b, t, q, val, 0, Plus())})
1764 if (not e.empty())
1765 {
1766 first.fail(s, e);
1767 break;
1768 }
1769 }, 2);
1770
1771 info.expect();
1772 getter.expect();
1773 max.expect();
1774 min.expect();
1775 user.expect();
1776 first.expect();
1777 update.expect();
1778 set.expect();
1779}
1780
1781TYPED_TEST(ExhaustiveTreeQueries, CentroidDecompositionMatchesItsDefinition)
1782{
1783 using GT = TypeParam;
1784 Check centroids("Gen_Centroid_Decomposition");
1785 Check first("Gen_Centroid_Decomposition rooted at the first node");
1786
1787 for_each_test_tree([&] (const Spec & s)
1788 {
1789 Built<GT> b(s);
1790 for (int r = 0; r < s.n; ++r)
1791 {
1792 const Rooted_Tree t(s, r);
1793 centroids.run();
1794 const Centroid_Decomposition<GT> cd(b.g, b.nodes[size_t(r)]);
1795 if (auto e = tree_error(b, t, cd); not e.empty())
1796 centroids.fail(s, "rooted at " + std::to_string(r) + ": " + e);
1797 else if (auto e2 = centroid_error(b, t, cd); not e2.empty())
1798 centroids.fail(s, "rooted at " + std::to_string(r) + ": " + e2);
1799 }
1800
1801 first.run();
1802 const Rooted_Tree t(s, num(b.g.get_first_node()));
1804 if (auto e = tree_error(b, t, cd); not e.empty())
1805 first.fail(s, e);
1806 else if (auto e2 = centroid_error(b, t, cd); not e2.empty())
1807 first.fail(s, e2);
1808 });
1809
1810 centroids.expect();
1811 first.expect();
1812}
1813
1814TYPED_TEST(ExhaustiveTreeQueries, HeavyLightDecompositionTakesExactlyTheTrees)
1815{
1816 using GT = TypeParam;
1817 using Filter = Hide_Mask<GT>;
1819 expect_takes_the_trees<GT>("Gen_Heavy_Light_Decomposition", false, true,
1820 [] (const Built<GT> & b, unsigned long hidden, typename GT::Node * root, int r)
1821 {
1822 return r == -1 ? Engine(b.g, Filter{hidden}) : Engine(b.g, root, Filter{hidden});
1823 },
1824 [] (const Built<GT> & b, const auto & e, const Rooted_Tree & t)
1825 {
1826 if (auto err = tree_error(b, t, e); not err.empty())
1827 return err;
1828 return decomposition_error(b, t, e);
1829 });
1830}
1831
1832TYPED_TEST(ExhaustiveTreeQueries, HldPathQueryTakesExactlyTheTrees)
1833{
1834 using GT = TypeParam;
1835 using Filter = Hide_Mask<GT>;
1836 using Engine = Gen_HLD_Path_Query<GT, int, Aleph::plus<int>, Filter>;
1837 expect_takes_the_trees<GT>("Gen_HLD_Path_Query", false, false,
1838 [] (const Built<GT> & b, unsigned long hidden, typename GT::Node * root, int r)
1839 {
1840 return r == -1 ? Engine(b.g, 0, Aleph::plus<int>(), Filter{hidden})
1841 : Engine(b.g, root, 0, Aleph::plus<int>(), Filter{hidden});
1842 },
1843 [] (const Built<GT> & b, const auto & e, const Rooted_Tree & t)
1844 {
1845 // The values are the infos, the numbers of the nodes
1846 std::vector<int> numbers;
1847 for (int x = 0; x < t.n; ++x)
1848 numbers.push_back(x);
1849 return path_query_error(b, t, e, numbers, 0, Plus());
1850 });
1851}
1852
1853TYPED_TEST(ExhaustiveTreeQueries, CentroidDecompositionTakesExactlyTheTrees)
1854{
1855 using GT = TypeParam;
1856 using Filter = Hide_Mask<GT>;
1858 expect_takes_the_trees<GT>("Gen_Centroid_Decomposition", false, false,
1859 [] (const Built<GT> & b, unsigned long hidden, typename GT::Node * root, int r)
1860 {
1861 return r == -1 ? Engine(b.g, Filter{hidden}) : Engine(b.g, root, Filter{hidden});
1862 },
1863 [] (const Built<GT> & b, const auto & e, const Rooted_Tree & t)
1864 {
1865 if (auto err = tree_error(b, t, e); not err.empty())
1866 return err;
1867 return centroid_error(b, t, e);
1868 });
1869}
1870
1871TYPED_TEST(ExhaustiveTreeQueries, TreeDecompositionsOnRandomTrees)
1872{
1873 using GT = TypeParam;
1874 using Node = typename GT::Node;
1875 Check hld("Gen_Heavy_Light_Decomposition");
1876 Check query("Gen_HLD_Path_Query, with updates");
1877 Check centroids("Gen_Centroid_Decomposition");
1878
1879 std::mt19937 rng(seed(7336));
1880 const int trees = heavy() ? 200 : 20;
1881 for (int k = 0; k < trees; ++k)
1882 {
1883 const Spec s = random_tree(rng, 8 + int(rng() % 41));
1884 Built<GT> b(s);
1885 const int r = int(rng() % unsigned(s.n));
1886 const Rooted_Tree t(s, r);
1887 const std::string at = "rooted at " + std::to_string(r) + ": ";
1888
1889 hld.run();
1890 const Gen_Heavy_Light_Decomposition<GT> h(b.g, b.nodes[size_t(r)]);
1891 if (auto e = tree_error(b, t, h); not e.empty())
1892 hld.fail(s, at + e);
1893 else if (auto e2 = decomposition_error(b, t, h); not e2.empty())
1894 hld.fail(s, at + e2);
1895
1896 std::vector<int> val = random_values(rng, s.n, -50, 50);
1897 auto nv = [&val] (Node * p) { return val[size_t(num(p))]; };
1898 Gen_HLD_Path_Query<GT> q(b.g, b.nodes[size_t(r)], nv, 0);
1899 for (int u = 0; u < 3; ++u)
1900 {
1901 query.run();
1902 if (auto e = path_query_error(b, t, q, val, 0, Plus(), u == 0); not e.empty())
1903 query.fail(s, at + e);
1904 const int x = int(rng() % unsigned(s.n));
1905 const int delta = int(rng() % 21) - 10;
1906 val[size_t(x)] += delta;
1907 q.update_node(b.nodes[size_t(x)], delta);
1908 }
1909
1910 centroids.run();
1911 const Gen_Centroid_Decomposition<GT> cd(b.g, b.nodes[size_t(r)]);
1912 if (auto e = tree_error(b, t, cd); not e.empty())
1913 centroids.fail(s, at + e);
1914 else if (auto e2 = centroid_error(b, t, cd); not e2.empty())
1915 centroids.fail(s, at + e2);
1916 }
1917
1918 hld.expect();
1919 query.expect();
1920 centroids.expect();
1921}
1922
1923// --------------------------------------------------------------------------
1924// Tree_DP.H
1925// --------------------------------------------------------------------------
1926
1927namespace
1928{
1931 char label(int x) { return char('0' + x); }
1932
1935 std::string canonical(const Rooted_Tree & t, int x)
1936 {
1937 std::vector<std::string> subs;
1938 for (int c : t.children[size_t(x)])
1939 subs.push_back("(" + canonical(t, c) + ")");
1940 std::sort(subs.begin(), subs.end());
1941 std::string r(1, label(x));
1942 for (const auto & sub : subs)
1943 r += sub;
1944 return r;
1945 }
1946
1950 std::string canonical(const std::string & text, size_t & pos)
1951 {
1952 if (pos >= text.size() or text[pos] == '(' or text[pos] == ')')
1953 return "";
1954 std::string r(1, text[pos++]);
1955 std::vector<std::string> subs;
1956 while (pos < text.size() and text[pos] == '(')
1957 {
1958 ++pos;
1959 const std::string sub = canonical(text, pos);
1960 if (sub.empty() or pos >= text.size() or text[pos] != ')')
1961 return "";
1962 ++pos;
1963 subs.push_back("(" + sub + ")");
1964 }
1965 std::sort(subs.begin(), subs.end());
1966 for (const auto & sub : subs)
1967 r += sub;
1968 return r;
1969 }
1970
1972 std::string canonical(const std::string & text)
1973 {
1974 size_t pos = 0;
1975 std::string r = canonical(text, pos);
1976 return pos == text.size() ? r : "";
1977 }
1978
1982 template <class GT, class DP>
1983 std::string subtree_sums_error(const Built<GT> & b, const Rooted_Tree & t, const DP & dp,
1984 const std::vector<int> & val)
1985 {
1986 if (auto e = tree_error(b, t, dp); not e.empty())
1987 return e;
1988 if (dp.values().size() != size_t(t.n))
1989 return std::to_string(dp.values().size()) + " values";
1990 for (int x = 0; x < t.n; ++x)
1991 {
1992 long long want = 0;
1993 for (int y : t.subtree(x))
1994 want += val[size_t(y)];
1995 auto * p = b.nodes[size_t(x)];
1996 if (dp.value(p) != want or dp.values()[dp.id_of(p)] != want)
1997 return "the subtree of " + std::to_string(x) + " sums " + std::to_string(dp.value(p))
1998 + ", not " + std::to_string(want);
1999 }
2000 return "";
2001 }
2002
2009 template <class GT, class Reroot, class Max, class Sums>
2010 std::string distances_error(const Built<GT> & b, const Rooted_Tree & t, const Reroot & dp,
2011 const Max & ecc, const Sums & sums, const std::vector<int> & val)
2012 {
2013 if (dp.size() != size_t(t.n) or dp.values().size() != size_t(t.n)
2014 or ecc.size() != size_t(t.n) or sums.size() != size_t(t.n))
2015 return "an answer without a place for each node";
2016 long long total = 0;
2017 for (int y = 0; y < t.n; ++y)
2018 total += val[size_t(y)];
2019 for (int x = 0; x < t.n; ++x)
2020 {
2021 auto * p = b.nodes[size_t(x)];
2022 const size_t i = dp.id_of(p);
2023 long long weighted = 0, far = 0, sum = 0;
2024 for (int y = 0; y < t.n; ++y)
2025 {
2026 const int d = t.distance(x, y);
2027 weighted += val[size_t(y)] * d;
2028 far = std::max<long long>(far, d);
2029 sum += d;
2030 }
2031 const std::string from = " from " + std::to_string(x);
2032 if (dp.value(p) != std::make_pair(total, weighted) or dp.values()[i] != dp.value(p))
2033 return "the weighted sum of the distances" + from + " is "
2034 + std::to_string(dp.value(p).second) + ", not " + std::to_string(weighted);
2035 if (ecc[i] != size_t(far))
2036 return "the greatest distance" + from + " is " + std::to_string(ecc[i]) + ", not "
2037 + std::to_string(far);
2038 if (sums[i] != size_t(sum))
2039 return "the sum of the distances" + from + " is " + std::to_string(sums[i]) + ", not "
2040 + std::to_string(sum);
2041 }
2042 return "";
2043 }
2044
2047 template <class GT, class SA = Dft_Show_Arc<GT>>
2048 Tree_DP<GT, std::string, SA> shape_dp(const Built<GT> & b, const Rooted_Tree & t,
2049 typename GT::Node * root, bool & wrong, SA sa = SA())
2050 {
2051 using Node = typename GT::Node;
2053 (b.g, root, [] (Node * p) { return std::string(1, label(num(p))); },
2054 [&t, &wrong] (Node * par, const std::string & acc, Node * child, const std::string & c)
2055 {
2056 if (t.parent[size_t(num(child))] != num(par) or acc.empty() or acc[0] != label(num(par))
2057 or c.empty() or c[0] != label(num(child)))
2058 wrong = true;
2059 return acc + "(" + c + ")";
2060 }, std::move(sa));
2061 }
2062
2065 template <class GT, class SA = Dft_Show_Arc<GT>>
2066 Reroot_DP<GT, std::string, SA> reroot_shape_dp(const Built<GT> & b, const Rooted_Tree & t,
2067 typename GT::Node * root, bool & wrong,
2068 SA sa = SA())
2069 {
2070 using Node = typename GT::Node;
2072 (b.g, root, std::string(), [] (Node * p) { return std::string(1, label(num(p))); },
2073 [] (const std::string & x, const std::string & y) { return x + y; },
2074 [&t, &wrong] (Node * p, Node * c, const std::string & x)
2075 {
2076 if (t.distance(num(p), num(c)) != 1 or x.empty() or x[0] != label(num(c)))
2077 wrong = true;
2078 return "(" + x + ")";
2079 }, std::move(sa));
2080 }
2081
2082 using Pair = std::pair<long long, long long>;
2083
2086 template <class GT, class SA = Dft_Show_Arc<GT>>
2087 Gen_Reroot_DP<GT, Pair, SA> weighted_dp(const Built<GT> & b, typename GT::Node * root,
2088 const std::vector<int> & val, SA sa = SA())
2089 {
2090 using Node = typename GT::Node;
2092 (b.g, root, Pair(0, 0), [&val] (Node * p) { return Pair(val[size_t(num(p))], 0); },
2093 [] (const Pair & x, const Pair & y) { return Pair(x.first + y.first, x.second + y.second); },
2094 [] (Node *, Node *, const Pair & x) { return Pair(x.first, x.second + x.first); },
2095 std::move(sa));
2096 }
2097
2099 template <class GT, class SA = Dft_Show_Arc<GT>>
2100 Gen_Tree_DP<GT, long long, SA> sums_dp(const Built<GT> & b, typename GT::Node * root,
2101 const std::vector<int> & val, SA sa = SA())
2102 {
2103 using Node = typename GT::Node;
2105 (b.g, root, [&val] (Node * p) { return (long long) val[size_t(num(p))]; },
2106 [] (Node *, const long long & acc, Node *, const long long & c) { return acc + c; },
2107 std::move(sa));
2108 }
2109}
2110
2111template <class GT>
2112class ExhaustiveTreeDp : public ::testing::Test {};
2113
2115
2116TYPED_TEST(ExhaustiveTreeDp, TreeDpFoldsEverySubtree)
2117{
2118 using GT = TypeParam;
2119 using Node = typename GT::Node;
2120 Check sums("Gen_Tree_DP, the sums over the subtrees");
2121 Check shape("Gen_Tree_DP, the subtrees that the combination sees");
2122 Check sizes("tree_subtree_sizes()");
2123 Check first("Gen_Tree_DP with the null root, rooted at the first node");
2124
2125 std::mt19937 rng(seed(7337));
2126 for_each_test_tree([&] (const Spec & s)
2127 {
2128 Built<GT> b(s);
2129 for (int r = -1; r < s.n; ++r)
2130 {
2131 const Rooted_Tree t(s, r == -1 ? num(b.g.get_first_node()) : r);
2132 Node * root = r == -1 ? nullptr : b.nodes[size_t(r)];
2133 const std::string at = r == -1 ? "" : "rooted at " + std::to_string(r) + ": ";
2134 const auto val = random_values(rng, s.n);
2135 Check & c = r == -1 ? first : sums;
2136
2137 c.run();
2138 const auto dp = sums_dp(b, root, val);
2139 if (auto e = subtree_sums_error(b, t, dp, val); not e.empty())
2140 c.fail(s, at + e);
2141
2142 shape.run();
2143 bool wrong = false;
2144 const auto sh = shape_dp(b, t, root, wrong);
2145 for (int x = 0; x < s.n and not wrong; ++x)
2146 if (canonical(sh.value(b.nodes[size_t(x)])) != canonical(t, x))
2147 {
2148 shape.fail(s, at + "the subtree of " + std::to_string(x) + " is "
2149 + sh.value(b.nodes[size_t(x)]) + ", not " + canonical(t, x));
2150 break;
2151 }
2152 if (wrong)
2153 shape.fail(s, at + "a combination of a node with one that is not its child");
2154
2155 sizes.run();
2156 const auto z = tree_subtree_sizes(b.g, root);
2157 bool ok = z.size() == size_t(s.n);
2158 for (int x = 0; ok and x < s.n; ++x)
2159 ok = z[dp.id_of(b.nodes[size_t(x)])] == size_t(t.size[size_t(x)]);
2160 if (not ok)
2161 sizes.fail(s, at + "wrong sizes");
2162 }
2163 });
2164
2165 sums.expect();
2166 shape.expect();
2167 sizes.expect();
2168 first.expect();
2169}
2170
2171TYPED_TEST(ExhaustiveTreeDp, RerootDpAnswersForEveryRoot)
2172{
2173 using GT = TypeParam;
2174 using Node = typename GT::Node;
2175 Check shape("Gen_Reroot_DP, the tree from each node");
2176 Check distances("Gen_Reroot_DP, tree_max_distance() and tree_sum_of_distances()");
2177
2178 std::mt19937 rng(seed(7338));
2179 for_each_test_tree([&] (const Spec & s)
2180 {
2181 Built<GT> b(s);
2182 std::vector<std::string> canon;
2183 for (int x = 0; x < s.n; ++x)
2184 canon.push_back(canonical(Rooted_Tree(s, x), x));
2185 for (int r = -1; r < s.n; ++r)
2186 {
2187 const Rooted_Tree t(s, r == -1 ? num(b.g.get_first_node()) : r);
2188 Node * root = r == -1 ? nullptr : b.nodes[size_t(r)];
2189 const std::string at = r == -1 ? "the null root: " : "rooted at " + std::to_string(r) + ": ";
2190
2191 shape.run();
2192 bool wrong = false;
2193 const auto sh = reroot_shape_dp(b, t, root, wrong);
2194 if (auto e = tree_error(b, t, sh); not e.empty())
2195 shape.fail(s, at + e);
2196 else
2197 for (int x = 0; x < s.n and not wrong; ++x)
2198 if (canonical(sh.value(b.nodes[size_t(x)])) != canon[size_t(x)]
2199 or sh.values()[sh.id_of(b.nodes[size_t(x)])] != sh.value(b.nodes[size_t(x)]))
2200 {
2201 shape.fail(s, at + "the tree from " + std::to_string(x) + " is "
2202 + sh.value(b.nodes[size_t(x)]) + ", not " + canon[size_t(x)]);
2203 break;
2204 }
2205 if (wrong)
2206 shape.fail(s, at + "an arc applied to two nodes that it does not join");
2207
2208 distances.run();
2209 const auto val = random_values(rng, s.n);
2210 if (auto e = distances_error(b, t, weighted_dp(b, root, val),
2212 tree_sum_of_distances(b.g, root), val);
2213 not e.empty())
2214 distances.fail(s, at + e);
2215 }
2216 }, 2);
2217
2218 shape.expect();
2219 distances.expect();
2220}
2221
2222TYPED_TEST(ExhaustiveTreeDp, TreeDpTakesTheTreesAndCountsParallelArcsOnce)
2223{
2224 using GT = TypeParam;
2225 using Filter = Hide_Mask<GT>;
2226 // No constructor without a root: -1 is the null root, as -2
2227 expect_takes_the_trees<GT>("Gen_Tree_DP", true, true,
2228 [] (const Built<GT> & b, unsigned long hidden, typename GT::Node * root, int)
2229 {
2230 return sums_dp(b, root, values_of(b), Filter{hidden});
2231 },
2232 [] (const Built<GT> & b, const auto & e, const Rooted_Tree & t)
2233 {
2234 return subtree_sums_error(b, t, e, values_of(b));
2235 });
2236}
2237
2238namespace
2239{
2242 template <class GT, class SA>
2243 struct Distances
2244 {
2246 Array<size_t> ecc;
2247 Array<size_t> sums;
2248
2249 [[nodiscard]] size_t size() const noexcept { return dp.size(); }
2250 };
2251}
2252
2253TYPED_TEST(ExhaustiveTreeDp, RerootDpTakesTheTreesAndCountsParallelArcsOnce)
2254{
2255 using GT = TypeParam;
2256 using Filter = Hide_Mask<GT>;
2257 expect_takes_the_trees<GT>("Gen_Reroot_DP, tree_max_distance() and tree_sum_of_distances()", true, false,
2258 [] (const Built<GT> & b, unsigned long hidden, typename GT::Node * root, int)
2259 {
2260 return Distances<GT, Filter>{weighted_dp(b, root, values_of(b), Filter{hidden}),
2261 tree_max_distance(b.g, root, Filter{hidden}),
2262 tree_sum_of_distances(b.g, root, Filter{hidden})};
2263 },
2264 [] (const Built<GT> & b, const auto & e, const Rooted_Tree & t)
2265 {
2266 return distances_error(b, t, e.dp, e.ecc, e.sums, values_of(b));
2267 });
2268}
2269
2270TYPED_TEST(ExhaustiveTreeDp, TreeDpOnRandomTrees)
2271{
2272 using GT = TypeParam;
2273 Check sums("Gen_Tree_DP, the sums over the subtrees");
2274 Check shape("Gen_Reroot_DP, the tree from each node");
2275 Check distances("Gen_Reroot_DP, tree_max_distance() and tree_sum_of_distances()");
2276
2277 std::mt19937 rng(seed(7339));
2278 const int trees = heavy() ? 200 : 20;
2279 for (int k = 0; k < trees; ++k)
2280 {
2281 const Spec s = random_tree(rng, 8 + int(rng() % 41));
2282 Built<GT> b(s);
2283 const int r = int(rng() % unsigned(s.n));
2284 const Rooted_Tree t(s, r);
2285 const auto val = random_values(rng, s.n, -50, 50);
2286 const std::string at = "rooted at " + std::to_string(r) + ": ";
2287
2288 sums.run();
2289 if (auto e = subtree_sums_error(b, t, sums_dp(b, b.nodes[size_t(r)], val), val); not e.empty())
2290 sums.fail(s, at + e);
2291
2292 shape.run();
2293 bool wrong = false;
2294 const auto sh = reroot_shape_dp(b, t, b.nodes[size_t(r)], wrong);
2295 for (int x = 0; x < s.n and not wrong; ++x)
2296 if (canonical(sh.value(b.nodes[size_t(x)])) != canonical(Rooted_Tree(s, x), x))
2297 {
2298 shape.fail(s, at + "the tree from " + std::to_string(x));
2299 break;
2300 }
2301 if (wrong)
2302 shape.fail(s, at + "an arc applied to two nodes that it does not join");
2303
2304 distances.run();
2305 if (auto e = distances_error(b, t, weighted_dp(b, b.nodes[size_t(r)], val),
2306 tree_max_distance(b.g, b.nodes[size_t(r)]),
2307 tree_sum_of_distances(b.g, b.nodes[size_t(r)]), val);
2308 not e.empty())
2309 distances.fail(s, at + e);
2310 }
2311
2312 sums.expect();
2313 shape.expect();
2314 distances.expect();
2315}
2316
2317// --------------------------------------------------------------------------
2318// tpl_mo_on_trees.H
2319// --------------------------------------------------------------------------
2320
2321namespace
2322{
2325 struct Window_Values
2326 {
2327 using answer_type = std::vector<int>;
2328
2329 std::multiset<int> window;
2330 bool broken = false;
2331
2332 void init(const Array<int> &, size_t)
2333 {
2334 window.clear();
2335 broken = false;
2336 }
2337
2338 void add(const Array<int> & data, size_t i) { window.insert(data[i]); }
2339
2340 void remove(const Array<int> & data, size_t i)
2341 {
2342 const auto it = window.find(data[i]);
2343 if (it == window.end())
2344 broken = true;
2345 else
2346 window.erase(it);
2347 }
2348
2349 [[nodiscard]] answer_type answer() const
2350 {
2351 if (broken)
2352 return {-1000};
2353 return {window.begin(), window.end()};
2354 }
2355 };
2356
2359 struct Window_Of
2360 {
2361 const std::vector<int> * val = nullptr;
2362
2363 std::string operator () (const std::vector<int> & nodes, const std::vector<int> & got) const
2364 {
2365 std::vector<int> want;
2366 for (int x : nodes)
2367 want.push_back((*val)[size_t(x)]);
2368 std::sort(want.begin(), want.end());
2369 return got == want ? "" : "gives " + text(got) + ", not " + text(want);
2370 }
2371 };
2372
2375 struct Distinct_Of
2376 {
2377 const std::vector<int> * val = nullptr;
2378
2379 std::string operator () (const std::vector<int> & nodes, size_t got) const
2380 {
2381 std::set<int> seen;
2382 for (int x : nodes)
2383 seen.insert((*val)[size_t(x)]);
2384 return got == seen.size() ? "" : "gives " + std::to_string(got) + ", not "
2385 + std::to_string(seen.size());
2386 }
2387 };
2388
2391 struct Powerful_Of
2392 {
2393 const std::vector<int> * val = nullptr;
2394
2395 std::string operator () (const std::vector<int> & nodes, long long got) const
2396 {
2397 std::vector<int> v;
2398 for (int x : nodes)
2399 v.push_back((*val)[size_t(x)]);
2400 long long want = 0;
2401 for (int a : std::set<int>(v.begin(), v.end()))
2402 {
2403 const long long c = std::count(v.begin(), v.end(), a);
2404 want += c * c * a;
2405 }
2406 return got == want ? "" : "gives " + std::to_string(got) + ", not " + std::to_string(want);
2407 }
2408 };
2409
2412 struct Mode_Of
2413 {
2414 const std::vector<int> * val = nullptr;
2415
2416 std::string operator () (const std::vector<int> & nodes, const std::pair<size_t, int> & got) const
2417 {
2418 std::vector<int> v;
2419 for (int x : nodes)
2420 v.push_back((*val)[size_t(x)]);
2421 size_t most = 0;
2422 for (int a : v)
2423 most = std::max(most, size_t(std::count(v.begin(), v.end(), a)));
2424 if (got.first != most or size_t(std::count(v.begin(), v.end(), got.second)) != most)
2425 return "gives the value " + std::to_string(got.second) + " counted "
2426 + std::to_string(got.first) + ", which is no mode of " + text(v);
2427 return "";
2428 }
2429 };
2430
2436 template <class Mo, class NodePtr, class Want>
2437 std::string mo_error(const Mo & mo, const std::vector<NodePtr> & node, const Rooted_Tree & t,
2438 const std::vector<int> & part, Want want)
2439 {
2440 if (mo.size() != part.size() or mo.is_empty() != part.empty())
2441 return "the size is " + std::to_string(mo.size());
2442
2443 Array<NodePtr> roots;
2444 for (int x : part)
2445 roots.append(node[size_t(x)]);
2446 const auto sub = mo.subtree_solve(roots);
2447 if (sub.size() != part.size())
2448 return std::to_string(sub.size()) + " answers for the subtrees";
2449 for (size_t k = 0; k < part.size(); ++k)
2450 if (auto e = want(t.subtree(part[k]), sub[k]); not e.empty())
2451 return "the subtree of " + std::to_string(part[k]) + " " + e;
2452
2454 for (int u : part)
2455 for (int v : part)
2456 pairs.append(std::make_pair(node[size_t(u)], node[size_t(v)]));
2457 const auto paths = mo.path_solve(pairs);
2458 if (paths.size() != pairs.size())
2459 return std::to_string(paths.size()) + " answers for the paths";
2460 size_t k = 0;
2461 for (int u : part)
2462 for (int v : part)
2463 if (auto e = want(t.path(u, v), paths[k++]); not e.empty())
2464 return "the path from " + std::to_string(u) + " to " + std::to_string(v) + " " + e;
2465
2466 const int a = part.front(), z = part.back();
2467 const auto il_sub = mo.subtree_solve({node[size_t(z)], node[size_t(a)]});
2468 const auto il_paths = mo.path_solve({{node[size_t(z)], node[size_t(a)]},
2469 {node[size_t(a)], node[size_t(z)]}});
2470 if (il_sub.size() != 2 or il_paths.size() != 2
2471 or not want(t.subtree(z), il_sub[0]).empty() or not want(t.subtree(a), il_sub[1]).empty()
2472 or not want(t.path(z, a), il_paths[0]).empty() or not want(t.path(a, z), il_paths[1]).empty())
2473 return "the overloads that take a list";
2474 if (mo.subtree_solve(Array<NodePtr>()).size() != 0
2475 or mo.path_solve(Array<std::pair<NodePtr, NodePtr>>()).size() != 0)
2476 return "answers without queries";
2477 return "";
2478 }
2479
2481 template <class GT>
2482 void set_values(Built<GT> & b, const std::vector<int> & val)
2483 {
2484 for (size_t x = 0; x < b.nodes.size(); ++x)
2485 b.nodes[x]->get_info() = val[x];
2486 }
2487
2490 template <class GT>
2491 void check_mo(const Spec & s, const Rooted_Tree & t, const std::vector<int> & val,
2492 const std::string & at, Check & window, Check & distinct, Check & powerful,
2493 Check & mode)
2494 {
2495 std::vector<int> all(size_t(s.n)), numbers(size_t(s.n));
2496 for (int x = 0; x < s.n; ++x)
2497 all[size_t(x)] = numbers[size_t(x)] = x;
2498
2499 // The policy of the user sees the numbers of the nodes; the others,
2500 // their values
2501 window.run();
2502 {
2503 Built<GT> b(s);
2504 const auto before = attributes(b);
2505 const Gen_Mo_On_Trees<GT, Window_Values> mo(b.g, b.nodes[size_t(t.root)]);
2506 if (auto e = mo_error(mo, b.nodes, t, all, Window_Of{&numbers}); not e.empty())
2507 window.fail(s, at + e);
2508 else if (attributes(b) != before)
2509 window.fail(s, at + "the graph changed");
2510 }
2511
2512 Built<GT> b(s);
2513 set_values(b, val);
2514 auto * root = b.nodes[size_t(t.root)];
2515 distinct.run();
2516 if (auto e = mo_error(Distinct_Count_Mo_On_Trees<GT>(b.g, root), b.nodes, t, all,
2517 Distinct_Of{&val}); not e.empty())
2518 distinct.fail(s, at + e);
2519 powerful.run();
2520 if (auto e = mo_error(Powerful_Array_Mo_On_Trees<GT>(b.g, root), b.nodes, t, all,
2521 Powerful_Of{&val}); not e.empty())
2522 powerful.fail(s, at + e);
2523 mode.run();
2524 if (auto e = mo_error(Range_Mode_Mo_On_Trees<GT>(b.g, root), b.nodes, t, all,
2525 Mode_Of{&val}); not e.empty())
2526 mode.fail(s, at + e);
2527 }
2528}
2529
2530template <class GT>
2531class ExhaustiveMoOnTrees : public ::testing::Test {};
2532
2534
2535TYPED_TEST(ExhaustiveMoOnTrees, MoAnswersOnEverySubtreeAndPath)
2536{
2537 using GT = TypeParam;
2538 const bool digraph = GT().is_digraph();
2539 Check window("Gen_Mo_On_Trees with a policy of the user");
2540 Check distinct("Distinct_Count_Mo_On_Trees");
2541 Check powerful("Powerful_Array_Mo_On_Trees");
2542 Check mode("Range_Mode_Mo_On_Trees");
2543 Check directions("Gen_Mo_On_Trees on a digraph with its arcs as inserted");
2544
2545 std::mt19937 rng(seed(7340));
2546 for_each_test_tree([&] (const Spec & s)
2547 {
2548 for (int r = 0; r < s.n; ++r)
2549 {
2550 const Rooted_Tree t(s, r);
2551 const auto val = random_values(rng, s.n);
2552 const std::string at = "rooted at " + std::to_string(r) + ": ";
2553 // A digraph has its arcs from the parents to the children
2554 check_mo<GT>(digraph ? from_root(s, t) : s, t, val, at, window, distinct, powerful, mode);
2555
2556 // As inserted, the arcs of a digraph may not reach every node
2557 if (not digraph)
2558 continue;
2559 directions.run();
2560 Built<GT> b(s);
2561 try
2562 {
2563 const Gen_Mo_On_Trees<GT, Window_Values> mo(b.g, b.nodes[size_t(r)]);
2564 std::vector<int> numbers(size_t(s.n)), all(size_t(s.n));
2565 for (int x = 0; x < s.n; ++x)
2566 numbers[size_t(x)] = all[size_t(x)] = x;
2567 if (not reaches_all(s, r))
2568 directions.fail(s, at + "takes a root that does not reach every node");
2569 else if (auto e = mo_error(mo, b.nodes, t, all, Window_Of{&numbers}); not e.empty())
2570 directions.fail(s, at + e);
2571 }
2572 catch (const std::domain_error &)
2573 {
2574 if (reaches_all(s, r))
2575 directions.fail(s, at + "rejects a root that reaches every node");
2576 }
2577 }
2578 }, 4);
2579
2580 window.expect();
2581 distinct.expect();
2582 powerful.expect();
2583 mode.expect();
2584 directions.expect();
2585}
2586
2587TYPED_TEST(ExhaustiveMoOnTrees, MoTakesWhatItDocuments)
2588{
2589 using GT = TypeParam;
2590 const bool digraph = GT().is_digraph();
2591 Check trees("Gen_Mo_On_Trees, the trees");
2592 Check rejected("Gen_Mo_On_Trees, a graph whose root does not reach every node");
2593 Check others("Gen_Mo_On_Trees, a connected graph that is not a tree");
2594 Check empty("Gen_Mo_On_Trees, the empty graph with the null root");
2595 Check empty_foreign("Gen_Mo_On_Trees, the empty graph with a root of another graph");
2596 Check foreign("Gen_Mo_On_Trees, a null root or one of another graph");
2597 Check queries("Gen_Mo_On_Trees, the queries on nodes out of the tree");
2598 Built<GT> other(Spec{1, {}, {}});
2599
2600 for_each_spec(domain(4, 3), digraph, [&] (const Spec & s)
2601 {
2602 Built<GT> b(s);
2603 std::vector<int> numbers(size_t(s.n)), all(size_t(s.n));
2604 for (int x = 0; x < s.n; ++x)
2605 numbers[size_t(x)] = all[size_t(x)] = x;
2606
2607 if (s.n == 0)
2608 {
2609 empty.run();
2610 try
2611 {
2612 const Gen_Mo_On_Trees<GT, Window_Values> mo(b.g, nullptr);
2613 if (mo.size() != 0 or not mo.is_empty()
2614 or mo.subtree_solve(Array<typename GT::Node *>()).size() != 0
2615 or not throws<std::domain_error>([&] { (void) mo.subtree_solve({other.nodes[0]}); }))
2616 empty.fail(s, "an engine that is not empty");
2617 }
2618 catch (const std::exception & ex)
2619 {
2620 empty.fail(s, std::string("throws ") + ex.what());
2621 }
2622 empty_foreign.run();
2623 if (not throws<std::domain_error>([&]
2624 { const Gen_Mo_On_Trees<GT, Window_Values> mo(b.g, other.nodes[0]); }))
2625 empty_foreign.fail(s, "takes a root of another graph");
2626 return;
2627 }
2628
2629 for (int r = 0; r < s.n; ++r)
2630 {
2631 // What it must take: the trees, as their arcs go from the root
2632 // in a digraph; and what it must reject: the graphs whose root
2633 // does not reach every node. A connected graph that is not a
2634 // tree breaks the precondition: it only must not crash.
2635 const bool reached = digraph ? reaches_all(s, r) : oracle::components(s) == 1;
2636 const bool tree = is_tree(s, 0) and (not digraph or reached);
2637 Check & c = tree ? trees : reached ? others : rejected;
2638 const std::string at = "rooted at " + std::to_string(r) + ": ";
2639 c.run();
2640 try
2641 {
2642 const Gen_Mo_On_Trees<GT, Window_Values> mo(b.g, b.nodes[size_t(r)]);
2643 if (not reached)
2644 c.fail(s, at + "takes a root that does not reach every node");
2645 else if (tree)
2646 {
2647 const Rooted_Tree t(s, r);
2648 if (auto e = mo_error(mo, b.nodes, t, all, Window_Of{&numbers}); not e.empty())
2649 c.fail(s, at + e);
2650 }
2651 else
2652 (void) mo.path_solve({{b.nodes[0], b.nodes[size_t(s.n - 1)]}});
2653
2654 // The queries on nodes out of the tree, from the last root
2655 if (r != s.n - 1)
2656 continue;
2657 queries.run();
2658 using Node = typename GT::Node;
2659 if (not throws<std::domain_error>([&] { (void) mo.subtree_solve({other.nodes[0]}); })
2660 or not throws<std::domain_error>([&] { (void) mo.subtree_solve({static_cast<Node *>(nullptr)}); })
2661 or not throws<std::domain_error>([&] { (void) mo.path_solve({{b.nodes[0], other.nodes[0]}}); })
2662 or not throws<std::domain_error>([&] { (void) mo.path_solve({{static_cast<Node *>(nullptr), b.nodes[0]}}); }))
2663 queries.fail(s, at + "answers on a node out of the tree");
2664 }
2665 catch (const std::domain_error &)
2666 {
2667 if (tree)
2668 c.fail(s, at + "rejects a tree");
2669 }
2670 }
2671
2672 foreign.run();
2673 if (not throws<std::domain_error>([&] { const Gen_Mo_On_Trees<GT, Window_Values> mo(b.g, nullptr); })
2674 or not throws<std::domain_error>([&] { const Gen_Mo_On_Trees<GT, Window_Values> mo(b.g, other.nodes[0]); }))
2675 foreign.fail(s, "takes a null root or one of another graph");
2676 });
2677
2678 trees.expect();
2679 rejected.expect();
2680 others.expect();
2681 empty.expect();
2682 empty_foreign.expect();
2683 foreign.expect();
2684 queries.expect();
2685}
2686
2688{
2689 using GT = TypeParam;
2690 const bool digraph = GT().is_digraph();
2691 Check window("Gen_Mo_On_Trees with a policy of the user");
2692 Check distinct("Distinct_Count_Mo_On_Trees");
2693 Check powerful("Powerful_Array_Mo_On_Trees");
2694 Check mode("Range_Mode_Mo_On_Trees");
2695
2696 std::mt19937 rng(seed(7341));
2697 const int trees = heavy() ? 100 : 10;
2698 for (int k = 0; k < trees; ++k)
2699 {
2700 const Spec s = random_tree(rng, 8 + int(rng() % 33));
2701 const int r = int(rng() % unsigned(s.n));
2702 const Rooted_Tree t(s, r);
2703 const auto val = random_values(rng, s.n, -3, 3);
2704 check_mo<GT>(digraph ? from_root(s, t) : s, t, val, "rooted at " + std::to_string(r) + ": ",
2705 window, distinct, powerful, mode);
2706 }
2707
2708 window.expect();
2709 distinct.expect();
2710 powerful.expect();
2711 mode.expect();
2712}
2713
2714namespace
2715{
2719 Tree_Node<int> * tree_nodes(const Rooted_Tree & t, std::vector<Tree_Node<int> *> & node,
2720 bool reversed)
2721 {
2722 node.assign(size_t(t.n), nullptr);
2723 for (int x = 0; x < t.n; ++x)
2724 node[size_t(x)] = new Tree_Node<int>(x);
2725 // From the root down, so that each child is still a leaf when it goes in
2726 for (int x : t.order)
2727 {
2728 auto ch = t.children[size_t(x)];
2729 if (reversed)
2730 std::reverse(ch.begin(), ch.end());
2731 for (int c : ch)
2732 node[size_t(x)]->insert_rightmost_child(node[size_t(c)]);
2733 }
2734 return node[size_t(t.root)];
2735 }
2736}
2737
2738TEST(ExhaustiveMoOnTreeNodes, MoAnswersOnEverySubtreeAndPath)
2739{
2740 Check window("Gen_Mo_On_Tree_Node with a policy of the user");
2741 Check distinct("Distinct_Count_Mo_On_Tree_Node");
2742 Check powerful("Powerful_Array_Mo_On_Tree_Node");
2743 Check mode("Range_Mode_Mo_On_Tree_Node");
2744 Check inner("Gen_Mo_On_Tree_Node from a node that has a parent");
2745 Check null("Gen_Mo_On_Tree_Node, the null root");
2746
2747 null.run();
2748 if (not throws<std::domain_error>([] { Gen_Mo_On_Tree_Node<int, Window_Values> mo(nullptr); }))
2749 null.fail(Spec(), "takes the null root");
2750
2751 std::mt19937 rng(seed(7342));
2752 for_each_test_tree([&] (const Spec & s)
2753 {
2754 for (int r = 0; r < s.n; ++r)
2755 {
2756 const Rooted_Tree t(s, r);
2757 const auto val = random_values(rng, s.n);
2758 const std::string at = "rooted at " + std::to_string(r) + ": ";
2759 std::vector<int> numbers(size_t(s.n)), all(size_t(s.n));
2760 for (int x = 0; x < s.n; ++x)
2761 numbers[size_t(x)] = all[size_t(x)] = x;
2762 std::vector<Tree_Node<int> *> node;
2763 Tree_Node<int> * root = tree_nodes(t, node, r % 2 == 1);
2764
2765 window.run();
2766 if (auto e = mo_error(Gen_Mo_On_Tree_Node<int, Window_Values>(root), node, t, all,
2767 Window_Of{&numbers}); not e.empty())
2768 window.fail(s, at + e);
2769
2770 // From a node with a parent, only its subtree; the rest is out
2771 inner.run();
2772 for (int c = 0; c < s.n; ++c)
2773 {
2774 if (c == r)
2775 continue;
2776 const auto part = t.subtree(c);
2777 const Gen_Mo_On_Tree_Node<int, Window_Values> mo(node[size_t(c)]);
2778 if (auto e = mo_error(mo, node, t, part, Window_Of{&numbers}); not e.empty())
2779 {
2780 inner.fail(s, at + "from " + std::to_string(c) + ": " + e);
2781 break;
2782 }
2783 if (not throws<std::domain_error>([&] { (void) mo.subtree_solve({node[size_t(r)]}); })
2784 or not throws<std::domain_error>([&] { (void) mo.path_solve({{node[size_t(c)], node[size_t(r)]}}); }))
2785 {
2786 inner.fail(s, at + "from " + std::to_string(c) + ": answers on a node out of it");
2787 break;
2788 }
2789 }
2790
2791 for (int x = 0; x < s.n; ++x)
2792 node[size_t(x)]->get_key() = val[size_t(x)];
2793 distinct.run();
2794 if (auto e = mo_error(Distinct_Count_Mo_On_Tree_Node<int>(root), node, t, all,
2795 Distinct_Of{&val}); not e.empty())
2796 distinct.fail(s, at + e);
2797 powerful.run();
2798 if (auto e = mo_error(Powerful_Array_Mo_On_Tree_Node<int>(root), node, t, all,
2799 Powerful_Of{&val}); not e.empty())
2800 powerful.fail(s, at + e);
2801 mode.run();
2802 if (auto e = mo_error(Range_Mode_Mo_On_Tree_Node<int>(root), node, t, all,
2803 Mode_Of{&val}); not e.empty())
2804 mode.fail(s, at + e);
2805
2807 }
2808 }, 4);
2809
2810 window.expect();
2811 distinct.expect();
2812 powerful.expect();
2813 mode.expect();
2814 inner.expect();
2815 null.expect();
2816}
2817
2818// --------------------------------------------------------------------------
2819// All the engines
2820// --------------------------------------------------------------------------
2821
2822TYPED_TEST(ExhaustiveTreeQueries, QueriesRejectWhatIsNotOfTheTree)
2823{
2824 using GT = TypeParam;
2825 using Node = typename GT::Node;
2826 Check lca("the LCA engines, the queries on what is not of the tree");
2827 Check hld("Gen_HLD, the queries on what is not of the tree");
2828 Check decomposition("the tree decompositions, the queries on what is not of the tree");
2829 Check dp("Gen_Tree_DP and Gen_Reroot_DP, the queries on what is not of the tree");
2830 Check empty("the engines of the empty graph");
2831 Built<GT> other(Spec{1, {}, {}});
2832 Node * const foreign = other.nodes[0];
2833 Node * const null = nullptr;
2834
2835 for (int n = 1; n <= 4; ++n)
2836 for_each_tree(n, 1, [&] (const Spec & s)
2837 {
2838 Built<GT> b(s);
2839 const size_t out = size_t(s.n); // the first id out of range
2840 for (int r = 0; r < s.n; ++r)
2841 {
2842 Node * const p = b.nodes[size_t(r)];
2843 const std::string at = "rooted at " + std::to_string(r);
2844 auto nv = [] (Node *) { return 1; };
2845
2846 // A null node or one of another graph is a logic error, and an
2847 // id out of range is out of range
2848 auto rejects_nodes = [&] (const auto & e)
2849 {
2850 for (Node * q : {null, foreign})
2851 if (not throws<std::logic_error>([&] { (void) e.id_of(q); })
2852 or not throws<std::logic_error>([&] { (void) e.lca(q, p); })
2853 or not throws<std::logic_error>([&] { (void) e.lca(p, q); })
2854 or not throws<std::logic_error>([&] { (void) e.distance(q, p); })
2855 or not throws<std::logic_error>([&] { (void) e.depth_of(q); })
2856 or not throws<std::logic_error>([&] { (void) e.parent_of(q); }))
2857 return false;
2858 return throws<std::out_of_range>([&] { (void) e.node_of(out); })
2859 and throws<std::out_of_range>([&] { (void) e.lca_id(out, 0); })
2860 and throws<std::out_of_range>([&] { (void) e.lca_id(0, out); })
2861 and throws<std::out_of_range>([&] { (void) e.distance_id(0, out); })
2862 and throws<std::out_of_range>([&] { (void) e.depth_of_id(out); })
2863 and throws<std::out_of_range>([&] { (void) e.parent_id(out); });
2864 };
2865
2866 lca.run();
2867 {
2868 const Binary_Lifting_LCA<GT> bl(b.g, p);
2869 const Euler_RMQ_LCA<GT> er(b.g, p);
2870 if (not rejects_nodes(bl) or not rejects_nodes(er)
2871 or not throws<std::logic_error>([&] { (void) bl.is_ancestor(foreign, p); })
2872 or not throws<std::logic_error>([&] { (void) er.is_ancestor(p, null); })
2873 or not throws<std::logic_error>([&] { (void) bl.kth_ancestor(foreign, 0); })
2874 or not throws<std::out_of_range>([&] { (void) bl.is_ancestor_id(out, 0); })
2875 or not throws<std::out_of_range>([&] { (void) er.is_ancestor_id(0, out); })
2876 or not throws<std::out_of_range>([&] { (void) bl.kth_ancestor_id(out, 0); }))
2877 lca.fail(s, at);
2878 }
2879
2880 hld.run();
2881 {
2882 HLD_Sum<GT, int> h(b.g, p, nv);
2883 if (not rejects_nodes(h)
2884 or not throws<std::logic_error>([&] { (void) h.path_query(foreign, p); })
2885 or not throws<std::logic_error>([&] { (void) h.subtree_query(null); })
2886 or not throws<std::logic_error>([&] { h.point_update(foreign, 1); })
2887 or not throws<std::logic_error>([&] { (void) h.get_value(null); })
2888 or not throws<std::out_of_range>([&] { (void) h.path_query_id(out, 0); })
2889 or not throws<std::out_of_range>([&] { (void) h.path_query_edges_id(0, out); })
2890 or not throws<std::out_of_range>([&] { (void) h.subtree_query_id(out); })
2891 or not throws<std::out_of_range>([&] { h.point_update_id(out, 1); })
2892 or not throws<std::out_of_range>([&] { (void) h.get_value_at_id(out); })
2893 or not throws<std::out_of_range>([&] { (void) h.position(out); })
2894 or not throws<std::out_of_range>([&] { (void) h.chain_head_id(out); })
2895 or not throws<std::out_of_range>([&] { (void) h.subtree_size_of_id(out); }))
2896 hld.fail(s, at);
2897 }
2898
2899 decomposition.run();
2900 {
2902 Gen_HLD_Path_Query<GT> q(b.g, p, 0);
2903 const Gen_Centroid_Decomposition<GT> cd(b.g, p);
2904 auto f = [] (size_t, size_t, bool) {};
2905 auto g = [] (size_t, size_t, size_t) {};
2906 if (not rejects_nodes(h)
2907 or not throws<std::logic_error>([&] { (void) h.heavy_child(foreign); })
2908 or not throws<std::logic_error>([&] { h.for_each_path_segment(p, null, f); })
2909 or not throws<std::out_of_range>([&] { (void) h.heavy_child_id(out); })
2910 or not throws<std::out_of_range>([&] { (void) h.head_id(out); })
2911 or not throws<std::out_of_range>([&] { (void) h.position_of_id(out); })
2912 or not throws<std::out_of_range>([&] { (void) h.subtree_range_id(out); })
2913 or not throws<std::out_of_range>([&] { (void) h.is_ancestor_id(0, out); })
2914 or not throws<std::out_of_range>([&] { h.for_each_path_segment_id(out, 0, f); })
2915 or not throws<std::logic_error>([&] { (void) q.query_path(foreign, p); })
2916 or not throws<std::logic_error>([&] { q.update_node(null, 1); })
2917 or not throws<std::out_of_range>([&] { (void) q.query_path_id(0, out); })
2918 or not throws<std::out_of_range>([&] { (void) q.query_subtree_id(out); })
2919 or not throws<std::out_of_range>([&] { q.update_node_id(out, 1); })
2920 or not throws<std::out_of_range>([&] { q.set_node_id(out, 1); })
2921 or not throws<std::out_of_range>([&] { (void) q.get_node_id(out); })
2922 or not throws<std::logic_error>([&] { (void) cd.id_of(foreign); })
2923 or not throws<std::logic_error>([&] { (void) cd.centroid_parent(null); })
2924 or not throws<std::logic_error>([&] { cd.for_each_centroid_ancestor(foreign, g); })
2925 or not throws<std::out_of_range>([&] { (void) cd.node_of(out); })
2926 or not throws<std::out_of_range>([&] { (void) cd.centroid_parent_id(out); })
2927 or not throws<std::out_of_range>([&] { (void) cd.centroid_level_of_id(out); })
2928 or not throws<std::out_of_range>([&] { (void) cd.centroid_path_length_of_id(out); })
2929 or not throws<std::out_of_range>([&] { (void) cd.centroid_ancestors_of_id(out); })
2930 or not throws<std::out_of_range>([&] { (void) cd.centroid_distances_of_id(out); })
2931 or not throws<std::out_of_range>([&] { (void) cd.is_centroid_ancestor_id(out, 0); })
2932 or not throws<std::out_of_range>([&] { (void) cd.distance_to_centroid_id(0, out); })
2933 or not throws<std::out_of_range>([&] { cd.for_each_centroid_ancestor_id(out, g); }))
2934 decomposition.fail(s, at);
2935 }
2936
2937 dp.run();
2938 {
2939 const std::vector<int> val(size_t(s.n), 1);
2940 const auto sums = sums_dp(b, p, val);
2941 const auto weighted = weighted_dp(b, p, val);
2942 if (not throws<std::logic_error>([&] { (void) sums.value(foreign); })
2943 or not throws<std::logic_error>([&] { (void) sums.value(null); })
2944 or not throws<std::logic_error>([&] { (void) sums.id_of(foreign); })
2945 or not throws<std::logic_error>([&] { (void) weighted.value(foreign); })
2946 or not throws<std::logic_error>([&] { (void) weighted.id_of(null); })
2947 or not throws<std::out_of_range>([&] { (void) sums.node_of(out); })
2948 or not throws<std::out_of_range>([&] { (void) weighted.node_of(out); }))
2949 dp.fail(s, at);
2950 }
2951 }
2952 });
2953
2954 // The engines of the empty graph are empty, and answer no query
2955 empty.run();
2956 {
2957 Spec s;
2958 Built<GT> b(s);
2959 auto nv = [] (Node *) { return 1; };
2960 const Gen_Binary_Lifting_LCA<GT> bl(b.g);
2961 const Gen_Euler_RMQ_LCA<GT> er(b.g);
2962 const HLD_Sum<GT, int> h(b.g, nv);
2964 const Gen_HLD_Path_Query<GT> q(b.g, 0);
2966 const std::vector<int> val;
2967 const auto sums = sums_dp(b, null, val);
2968 const auto weighted = weighted_dp(b, null, val);
2969 if (not bl.is_empty() or bl.size() != 0 or bl.root() != nullptr or bl.num_levels() != 0
2970 or not er.is_empty() or er.euler_tour_size() != 0 or not h.is_empty() or h.num_chains() != 0
2971 or not d.is_empty() or not q.is_empty() or q.size() != 0 or not cd.is_empty()
2972 or cd.centroid_root() != nullptr or cd.centroid_root_id() != No_Id
2973 or cd.max_centroid_level() != 0 or sums.size() != 0 or sums.values().size() != 0
2974 or weighted.size() != 0 or weighted.values().size() != 0
2975 or tree_subtree_sizes(b.g, null).size() != 0 or tree_max_distance(b.g, null).size() != 0
2976 or tree_sum_of_distances(b.g, null).size() != 0)
2977 empty.fail(s, "an engine that is not empty");
2978 if (not throws<std::logic_error>([&] { (void) bl.lca_id(0, 0); })
2979 or not throws<std::logic_error>([&] { (void) er.lca_id(0, 0); })
2980 or not throws<std::logic_error>([&] { (void) bl.depth_of_id(0); })
2981 or not throws<std::logic_error>([&] { (void) h.path_query_id(0, 0); })
2982 or not throws<std::logic_error>([&] { (void) h.subtree_query_id(0); })
2983 or not throws<std::logic_error>([&] { (void) d.lca_id(0, 0); })
2984 or not throws<std::logic_error>([&] { (void) q.query_path_id(0, 0); })
2985 or not throws<std::logic_error>([&] { (void) cd.for_each_centroid_ancestor_id(0, [] (size_t, size_t, size_t) {}); })
2986 or not throws<std::logic_error>([&] { (void) sums.node_of(0); }))
2987 empty.fail(s, "a query on the empty graph that does not throw");
2988
2989 // A root on the empty graph can only be of another graph
2990 if (not throws<std::domain_error>([&] { Gen_Binary_Lifting_LCA<GT> e(b.g, foreign); })
2991 or not throws<std::domain_error>([&] { Gen_Euler_RMQ_LCA<GT> e(b.g, foreign); })
2992 or not throws<std::domain_error>([&] { HLD_Sum<GT, int> e(b.g, foreign, nv); })
2993 or not throws<std::domain_error>([&] { Gen_Heavy_Light_Decomposition<GT> e(b.g, foreign); })
2994 or not throws<std::domain_error>([&] { Gen_HLD_Path_Query<GT> e(b.g, foreign, 0); })
2995 or not throws<std::domain_error>([&] { Gen_Centroid_Decomposition<GT> e(b.g, foreign); })
2996 or not throws<std::domain_error>([&] { (void) sums_dp(b, foreign, val); })
2997 or not throws<std::domain_error>([&] { (void) weighted_dp(b, foreign, val); }))
2998 empty.fail(s, "takes a root of another graph");
2999 }
3000
3001 lca.expect();
3002 hld.expect();
3003 decomposition.expect();
3004 dp.expect();
3005 empty.expect();
3006}
3007
3008namespace
3009{
3015 template <class GT, class Make, class Answer>
3016 std::string copies_error(const Built<GT> & b, int r, const Built<GT> & other, Make make,
3017 Answer answer)
3018 {
3019 const auto e = make(b, r);
3020 using E = std::remove_const_t<decltype(e)>;
3021 E copy(e);
3022 if (auto err = answer(copy); not err.empty())
3023 return "a copy: " + err;
3024 E moved(std::move(copy));
3025 if (auto err = answer(moved); not err.empty())
3026 return "a move: " + err;
3027 if constexpr (std::is_copy_assignable_v<E> and std::is_move_assignable_v<E>)
3028 {
3029 E assigned = make(other, 0);
3030 assigned = e;
3031 if (auto err = answer(assigned); not err.empty())
3032 return "a copy assigned: " + err;
3033 E move_assigned = make(other, 0);
3034 move_assigned = std::move(assigned);
3035 if (auto err = answer(move_assigned); not err.empty())
3036 return "a move assigned: " + err;
3037 }
3038 if (auto err = answer(e); not err.empty())
3039 return "the original after its copies: " + err;
3040 return "";
3041 }
3042}
3043
3044TYPED_TEST(ExhaustiveTreeQueries, CopiesAndMovesAnswerAsTheOriginal)
3045{
3046 using GT = TypeParam;
3047 using Node = typename GT::Node;
3048 Check lca("the LCA engines, their copies and moves");
3049 Check hld("Gen_HLD, its copies and moves");
3050 Check decomposition("the tree decompositions, their copies and moves");
3051 Check dp("Gen_Tree_DP and Gen_Reroot_DP, their copies and moves");
3052 Check mo("Gen_Mo_On_Trees, its copies and moves");
3053
3054 // Another tree, of other size and shape
3055 Spec star;
3056 star.n = 6;
3057 for (int x = 1; x < 6; ++x)
3058 star.arcs.push_back({0, x});
3059 Built<GT> other(star);
3060
3061 for (int n = 1; n <= 5; ++n)
3062 for_each_tree(n, n <= 4 ? 1 : 5, [&] (const Spec & s)
3063 {
3064 Built<GT> b(s);
3065 // Values for the nodes of both trees
3066 std::vector<int> val(size_t(other.g.get_num_nodes())), all(size_t(s.n)), numbers(size_t(s.n));
3067 for (size_t x = 0; x < val.size(); ++x)
3068 val[x] = 2 - int(x % 5);
3069 for (int x = 0; x < s.n; ++x)
3070 all[size_t(x)] = numbers[size_t(x)] = x;
3071 auto nv = [&val] (Node * p) { return val[size_t(num(p))]; };
3072 for (int r : {0, s.n - 1})
3073 {
3074 const Rooted_Tree t(s, r);
3075 const std::string at = "rooted at " + std::to_string(r) + ": ";
3076 auto tree = [&] (const auto & e) { return tree_error(b, t, e); };
3077
3078 lca.run();
3079 for (const auto & e : {copies_error(b, r, other, [] (const Built<GT> & g, int x)
3080 { return Binary_Lifting_LCA<GT>(g.g, g.nodes[size_t(x)]); },
3081 [&] (const auto & e) { return tree(e) + kth_error(b, t, e); }),
3082 copies_error(b, r, other, [] (const Built<GT> & g, int x)
3083 { return Euler_RMQ_LCA<GT>(g.g, g.nodes[size_t(x)]); },
3084 [&] (const auto & e) { return tree(e) + euler_tour_error(t, e); })})
3085 if (not e.empty())
3086 {
3087 lca.fail(s, at + e);
3088 break;
3089 }
3090
3091 hld.run();
3092 if (auto e = copies_error(b, r, other, [&] (const Built<GT> & g, int x)
3093 { return HLD_Sum<GT, int>(g.g, g.nodes[size_t(x)], nv); },
3094 [&] (const auto & e)
3095 { return tree(e) + hld_layout_error(b, t, e)
3096 + fold_error(b, t, e, val, 0, Plus(), false); });
3097 not e.empty())
3098 hld.fail(s, at + e);
3099
3100 decomposition.run();
3101 for (const auto & e : {copies_error(b, r, other, [] (const Built<GT> & g, int x)
3102 { return Gen_Heavy_Light_Decomposition<GT>(g.g, g.nodes[size_t(x)]); },
3103 [&] (const auto & e) { return tree(e) + decomposition_error(b, t, e); }),
3104 copies_error(b, r, other, [] (const Built<GT> & g, int x)
3105 { return Gen_HLD_Path_Query<GT>(g.g, g.nodes[size_t(x)], 0); },
3106 [&] (const auto & e) { return path_query_error(b, t, e, numbers, 0, Plus()); }),
3107 copies_error(b, r, other, [] (const Built<GT> & g, int x)
3108 { return Gen_Centroid_Decomposition<GT>(g.g, g.nodes[size_t(x)]); },
3109 [&] (const auto & e) { return tree(e) + centroid_error(b, t, e); })})
3110 if (not e.empty())
3111 {
3112 decomposition.fail(s, at + e);
3113 break;
3114 }
3115
3116 dp.run();
3117 for (const auto & e : {copies_error(b, r, other, [&] (const Built<GT> & g, int x)
3118 { return sums_dp(g, g.nodes[size_t(x)], val); },
3119 [&] (const auto & e) { return subtree_sums_error(b, t, e, val); }),
3120 copies_error(b, r, other, [&] (const Built<GT> & g, int x)
3121 { return weighted_dp(g, g.nodes[size_t(x)], val); },
3122 [&] (const auto & e)
3123 { return distances_error(b, t, e, tree_max_distance(b.g, b.nodes[size_t(r)]),
3124 tree_sum_of_distances(b.g, b.nodes[size_t(r)]), val); })})
3125 if (not e.empty())
3126 {
3127 dp.fail(s, at + e);
3128 break;
3129 }
3130
3131 mo.run();
3132 if (auto e = copies_error(b, r, other, [] (const Built<GT> & g, int x)
3133 { return Gen_Mo_On_Trees<GT, Window_Values>(g.g, g.nodes[size_t(x)]); },
3134 [&] (const auto & e) { return mo_error(e, b.nodes, t, all, Window_Of{&numbers}); });
3135 not e.empty())
3136 mo.fail(s, at + e);
3137 }
3138 });
3139
3140 lca.expect();
3141 hld.expect();
3142 decomposition.expect();
3143 dp.expect();
3144 mo.expect();
3145}
3146
3147TYPED_TEST(ExhaustiveTreeQueries, LongPathsAndStarsRunOnASmallStack)
3148{
3149 using GT = TypeParam;
3150 using Node = typename GT::Node;
3151 const int path_size = heavy() ? 100000 : 10000;
3152 auto total = [] (const Array<size_t> & a)
3153 {
3154 long long r = 0;
3155 for (size_t i = 0; i < a.size(); ++i)
3156 r += (long long) a[i];
3157 return r;
3158 };
3159 auto greatest = [] (const Array<size_t> & a)
3160 {
3161 long long r = 0;
3162 for (size_t i = 0; i < a.size(); ++i)
3163 r = std::max(r, (long long) a[i]);
3164 return r;
3165 };
3166
3167 // The path is deep, and the star, of a fifth of its nodes, broad
3168 for (const bool path : {true, false})
3169 {
3170 Spec s;
3171 s.n = path ? path_size : path_size / 5;
3172 const int n = s.n;
3173 for (int x = 1; x < n; ++x)
3174 s.arcs.push_back({path ? x - 1 : 0, x});
3175 Built<GT> b(s);
3176 Node * first = b.nodes[0];
3177 Node * last = b.nodes[size_t(n - 1)];
3178 const size_t far = path ? size_t(n - 1) : 1;
3179 std::string error;
3180
3181 const bool ran = run_with_small_stack([&]
3182 {
3183 try
3184 {
3185 auto nv = [] (Node *) { return 1; };
3186 const Binary_Lifting_LCA<GT> bl(b.g, first);
3187 const Euler_RMQ_LCA<GT> er(b.g, first);
3188 const HLD_Sum<GT, int> h(b.g, first, nv);
3189 const Gen_Heavy_Light_Decomposition<GT> d(b.g, first);
3190 const Gen_HLD_Path_Query<GT> q(b.g, first, nv, 0);
3191 const Gen_Centroid_Decomposition<GT> cd(b.g, first);
3192 const auto sizes = tree_subtree_sizes(b.g, first);
3193 const auto sums = tree_sum_of_distances(b.g, first);
3194 const Distinct_Count_Mo_On_Trees<GT> mo(b.g, first);
3195 const auto mo_sub = mo.subtree_solve({first, last});
3196 const auto mo_path = mo.path_solve({{first, last}, {last, last}});
3197 if (bl.depth_of(last) != far or bl.lca(last, first) != first
3198 or bl.distance(first, last) != far or bl.kth_ancestor(last, far) != first)
3199 error = "Gen_Binary_Lifting_LCA";
3200 else if (er.depth_of(last) != far or er.lca(first, last) != first
3201 or er.euler_tour_size() != size_t(2 * n - 1))
3202 error = "Gen_Euler_RMQ_LCA";
3203 else if (h.path_query(first, last) != int(far) + 1 or h.subtree_query(first) != n
3204 or h.distance(last, first) != far)
3205 error = "Gen_HLD";
3206 else if (d.lca(last, first) != first or d.distance(first, last) != far
3207 or q.query_path(last, first) != int(far) + 1 or q.query_subtree(first) != n)
3208 error = "Gen_Heavy_Light_Decomposition and Gen_HLD_Path_Query";
3209 else if (int(cd.max_centroid_level()) > floor_log2(size_t(n)))
3210 error = "Gen_Centroid_Decomposition";
3211 else if (sizes.size() != size_t(n) or sums.size() != size_t(n)
3212 or total(sizes) != (path ? n * (n + 1LL) / 2 : 2LL * n - 1)
3213 or greatest(sums) != (path ? n * (n - 1LL) / 2 : 2LL * n - 3))
3214 error = "tree_subtree_sizes() and tree_sum_of_distances()";
3215 else if (mo_sub[0] != size_t(n) or mo_sub[1] != 1 or mo_path[0] != far + 1
3216 or mo_path[1] != 1)
3217 error = "Distinct_Count_Mo_On_Trees";
3218 }
3219 catch (const std::exception & ex)
3220 {
3221 error = std::string("throws ") + ex.what();
3222 }
3223 });
3224
3225 EXPECT_TRUE(ran) << "the thread with a small stack could not run";
3226 EXPECT_EQ(error, "") << (path ? "a path" : "a star") << " of " << n << " nodes";
3227 }
3228}
Heavy-Light Decomposition for tree path queries on Aleph graphs.
Lowest Common Ancestor (LCA) on rooted trees represented as Aleph graphs.
Generic tree dynamic programming and rerooting algorithms.
Heavy-Light and Centroid decomposition on rooted trees represented as Aleph graphs.
WeightedDigraph::Node Node
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
long double hd
Definition btreepic.C:151
long double h
Definition btreepic.C:154
size_t size_t int32_t * out
Definition ca-c-api.h:120
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
LCA via binary lifting on a rooted tree.
Definition LCA.H:539
size_t depth_of(const Node *node) const
Distance from root to node.
Definition LCA.H:729
size_t depth_of_id(const size_t id) const
Distance from root to node by ID.
Definition LCA.H:722
bool is_empty() const noexcept
Returns true if the tree has no nodes.
Definition LCA.H:685
size_t num_levels() const noexcept
Returns the number of levels in the jump table: , or 0 if the tree is empty.
Definition LCA.H:704
bool is_ancestor(const Node *u, const Node *v) const
Returns true if node u is an ancestor of v (or u == v).
Definition LCA.H:755
Node * kth_ancestor(const Node *node, const size_t k) const
k-th ancestor by node pointer in O(log n).
Definition LCA.H:778
size_t kth_ancestor_id(const size_t id, const size_t k) const
k-th ancestor by id in O(log n).
Definition LCA.H:766
Node * root() const noexcept
Returns the root node of the tree.
Definition LCA.H:691
bool is_ancestor_id(const size_t u, const size_t v) const
Returns true if node u is an ancestor of v (or u == v).
Definition LCA.H:749
size_t distance(const Node *u, const Node *v) const
Number of edges on the path between two nodes in O(log n).
Definition LCA.H:829
size_t size() const noexcept
Total number of nodes in the tree.
Definition LCA.H:679
size_t lca_id(size_t u, size_t v) const
LCA query by node ids in O(log n).
Definition LCA.H:785
Node * lca(const Node *u, const Node *v) const
LCA query by node pointers in O(log n).
Definition LCA.H:816
Centroid decomposition over a rooted tree represented as an Aleph graph.
Node * centroid_parent(const Node *node) const
Parent centroid of node (or nullptr if centroid root).
size_t centroid_level_of_id(const size_t id) const
Level of centroid id in centroid tree (root level = 0).
Node * centroid_root() const noexcept
Root centroid node of the centroid tree (or nullptr if empty).
bool is_centroid_ancestor_id(const size_t ancestor, const size_t node) const
True iff ancestor is in the centroid-ancestor chain of node.
size_t centroid_root_id() const noexcept
Root centroid ID of the centroid tree (or NONE if empty).
const Array< size_t > & centroid_ancestors_of_id(const size_t id) const
Centroid ancestors of node ID from centroid root down to local centroid.
Node * node_of(const size_t id) const
size_t centroid_parent_id(const size_t id) const
Parent centroid ID of id (or NONE if centroid root).
size_t centroid_path_length_of_id(const size_t id) const
Number of centroid ancestors stored for node ID.
size_t max_centroid_level() const noexcept
Maximum centroid-tree level.
size_t distance_to_centroid_id(const size_t node, const size_t centroid) const
Distance from node ID to a centroid ancestor ID.
void for_each_centroid_ancestor_id(const size_t node, F &&f) const
Visit each centroid ancestor of node ID.
size_t id_of(const Node *node) const
void for_each_centroid_ancestor(const Node *node, F &&f) const
Visit each centroid ancestor of node.
const Array< size_t > & centroid_distances_of_id(const size_t id) const
Distances to centroid ancestors (aligned with centroid_ancestors_of_id).
LCA via Euler tour + RMQ on depth in a rooted tree.
Definition LCA.H:857
bool is_empty() const noexcept
Returns true if the tree has no nodes.
Definition LCA.H:971
bool is_ancestor(const Node *u, const Node *v) const
Returns true if node u is an ancestor of v (or u == v).
Definition LCA.H:1034
size_t lca_id(const size_t u, const size_t v) const
LCA query by node ids in O(1).
Definition LCA.H:1040
size_t depth_of(const Node *node) const
Distance from root to node.
Definition LCA.H:1008
Node * lca(const Node *u, const Node *v) const
LCA query by node pointers in O(1).
Definition LCA.H:1055
bool is_ancestor_id(const size_t u, const size_t v) const
Returns true if node u is an ancestor of v (or u == v).
Definition LCA.H:1028
size_t euler_tour_size() const noexcept
Euler tour size ( for empty tree, else ).
Definition LCA.H:1080
Segment-tree-powered path/subtree queries over an HLD layout.
T query_subtree(const Node *node) const
Subtree query for node in O(log n).
void set_node(const Node *node, const T &value)
Point assignment: a[node] = value.
T query_path(const Node *u, const Node *v) const
Path query between two nodes in O(log^2 n).
void update_node(const Node *node, const T &delta)
Point update: a[node] = Op(a[node], delta).
const Gen_Heavy_Light_Decomposition< GT, SA > & decomposition() const noexcept
T query_path_id(const size_t u, const size_t v) const
Path query between two node IDs in O(log^2 n).
T get_node_id(const size_t id) const
Return current value at node ID.
size_t size() const noexcept
T query_subtree_id(const size_t id) const
Subtree query for node ID in O(log n).
void update_node_id(const size_t id, const T &delta)
Point update: a[id] = Op(a[id], delta).
bool is_empty() const noexcept
void set_node_id(const size_t id, const T &value)
Point assignment: a[id] = value.
Heavy-Light Decomposition with segment tree for path/subtree queries.
Definition HLD.H:624
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
size_t id_of(const Node *node) const
Map a Node pointer to its internal ID.
Definition HLD.H:824
void point_update(const Node *v, const T &new_value)
Point update by node pointer: set value to new_value.
Definition HLD.H:1023
Heavy-Light Decomposition over a rooted tree represented as an Aleph graph.
size_t lca_id(size_t u, size_t v) const
Lowest common ancestor in O(log n).
size_t distance(const Node *u, const Node *v) const
Distance (number of edges) between two nodes.
Node * lca(const Node *u, const Node *v) const
Lowest common ancestor in O(log n).
Offline subtree and path queries on N-ary trees (Tree_Node).
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(const Array< Node * > &query_roots) const
Answer subtree queries on the N-ary tree.
Offline subtree and path queries on trees via Mo's algorithm.
Array< answer_type > subtree_solve(const Array< Node * > &query_roots) const
Answer subtree queries using Mo's algorithm.
bool is_empty() const noexcept
True if the tree is empty.
size_t size() const noexcept
Number of nodes in the tree.
Array< answer_type > path_solve(const Array< std::pair< Node *, Node * > > &query_pairs) const
Answer path queries between node pairs.
Generic rerooting dynamic programming (all-roots DP).
Definition Tree_DP.H:544
size_t size() const noexcept
Returns the number of nodes in the tree.
Definition Tree_DP.H:688
Generic bottom-up tree dynamic programming.
Definition Tree_DP.H:406
Node * get_first_node() const
Return any node in the graph.
Definition tpl_graph.H:590
Forward declaration used by CRTP helpers before the full node definition.
iterator end() noexcept
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
Container< Node * > nodes() const
Return a container with all the nodes of the graph.
Definition graph-dry.H:3062
The failures of one property over a domain.
void expect() const
Expects what the mark says, and prints the first failures.
void fail(const Spec &s, const std::string &what)
Counts a failure on spec, with what went wrong.
void run() noexcept
Counts a run of the property.
BinNode< int > * random_tree(int l, int r)
Recursively build a random binary search tree.
Definition deway.C:187
#define TEST(name)
static mt19937 rng
static Tree_Node< int > * chain(size_t n)
__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
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
__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
TYPED_TEST_SUITE(ExhaustiveTreeQueries, Undirected_Kinds)
TYPED_TEST(ExhaustiveTreeQueries, LcaEnginesAnswerEveryQuery)
The kinds of arc filter and of distance that the graph algorithms must accept.
Every small multigraph, on every kind of graph, for the tests.
Answers computed from a Spec of graph_harness.H, without Aleph.
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
@ Num_Bits_Graph
Definition aleph-graph.H:85
void destroy_tree(Node *root)
Destroys (frees memory) the tree whose root is root.
static mpfr_t y
Definition mpfr_mul_d.c:3
size_t degree(const GT &g, typename GT::Node *p, SA &sa)
Degree of a node as an Eulerian walk counts it.
Definition eulerian.H:129
Main namespace for Aleph-w library functions.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
Definition ahTypes.H:123
Array< size_t > tree_subtree_sizes(const GT &g, typename GT::Node *root, SA sa=SA())
Compute subtree sizes for every node.
Definition Tree_DP.H:732
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
Fw_Itor remove(Fw_Itor __first, const Fw_Itor &__last, const T &__value)
Remove elements equal to a value.
Definition ahAlgo.H:962
Itor1 search(Itor1 beg, const Itor1 &end, Itor2 searchBeg, const Itor2 &searchEnd, BinaryPredicate op=BinaryPredicate())
Search for a subrange within a range.
Definition ahAlgo.H:309
@ Tree
Basic arc (in spanning tree).
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
void error(const char *file, int line, const char *format,...)
Print an error message with file and line info.
Definition ahDefs.C:100
std::ostream & join(const C &c, const std::string &sep, std::ostream &out)
Join elements of an Aleph-style container into a stream.
Container< T > range(const T start, const T end, const T step=1)
Generate a range of values [start, end] with a given step.
Array< size_t > tree_max_distance(const GT &g, typename GT::Node *root, SA sa=SA())
Compute the maximum distance from each node to any leaf.
Definition Tree_DP.H:767
Array< size_t > tree_sum_of_distances(const GT &g, typename GT::Node *root, SA sa=SA())
Compute sum of distances from each node to all others.
Definition Tree_DP.H:805
static std::atomic< bool > init
Definition hash-fct.C:54
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
double sub(double a, double b)
double add(double a, double b)
constexpr bool shown(unsigned long hidden, int i) noexcept
Whether the arc number i is shown by the mask hidden.
bool run_with_small_stack(F &&f, size_t kb=256)
Runs f in a thread whose stack has kb KiB, and returns false if the thread could not run; without POS...
GT::Node * node_of(const GT &g, int i)
The node of a graph whose number is i.
Mode mode()
ALEPH_GRAPH_HARNESS=light, normal or heavy, or else light in a build with a sanitizer and normal with...
::testing::Types< Aleph::List_Graph< Aleph::Graph_Node< int >, Aleph::Graph_Arc< int > >, Aleph::List_SGraph< Aleph::Graph_Snode< int >, Aleph::Graph_Sarc< int > >, Aleph::Array_Graph< Aleph::Graph_Anode< int >, Aleph::Graph_Aarc< int > > > Undirected_Kinds
The kinds of graph that are not directed, with int infos.
size_t for_each_spec(const Domain &d, bool directed, F &&f)
Calls f(spec) with every spec of d, smallest first, and returns how many there were.
int num(Node *p)
The number of a node of a built graph.
Domain domain(int max_nodes, int max_arcs)
The domain of max_nodes nodes and max_arcs arcs, of one more of each in heavy mode,...
bool heavy()
Whether the mode is heavy, which asks for the larger domains.
::testing::Types< Aleph::List_Graph< Aleph::Graph_Node< int >, Aleph::Graph_Arc< int > >, Aleph::List_SGraph< Aleph::Graph_Snode< int >, Aleph::Graph_Sarc< int > >, Aleph::Array_Graph< Aleph::Graph_Anode< int >, Aleph::Graph_Aarc< int > >, Aleph::List_Digraph< Aleph::Graph_Node< int >, Aleph::Graph_Arc< int > >, Aleph::List_SDigraph< Aleph::Graph_Snode< int >, Aleph::Graph_Sarc< int > >, Aleph::Array_Digraph< Aleph::Graph_Anode< int >, Aleph::Graph_Aarc< int > > > All_Kinds
The six kinds, with int infos.
std::vector< std::vector< bool > > closure(const Spec &s, bool directed)
reach[u][v]: v is reached from u by a directed path of one arc or more (in a graph that is not direct...
bool reaches(const std::vector< std::vector< bool > > &r, int u, int v)
Whether there is a path, of zero arcs or more, from u to v.
int components(const Spec &s, int skip_node=-1, int skip_arc=-1)
The number of components, without the node skip_node and the arc skip_arc.
Spec reversed(const Spec &s)
The spec with each arc reversed; the arcs keep their numbers.
STL namespace.
HLD with path/subtree max queries.
Definition HLD.H:1172
HLD with path/subtree min queries.
Definition HLD.H:1199
HLD with path/subtree sum queries.
Definition HLD.H:1145
Hides the arcs of a mask; copyable, assignable, noexcept.
A graph made from a spec, with its nodes and arcs by number.
std::vector< typename GT::Node * > nodes
A small multigraph: its nodes are 0 .
size_t num_arcs() const noexcept
std::vector< std::array< int, 2 > > arcs
Union-find over the nodes 0 .. n - 1.
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Gsl_Compatible_Rng r
Generic graph and digraph implementations.
Mo's algorithm on trees: offline subtree and path queries.
General tree (n-ary tree) node.
DynList< int > l