|
3 | 3 | #include "ascending_dfs.hpp" |
4 | 4 | #include "../graph/base.hpp" |
5 | 5 | #include "../util/big_alloc.hpp" |
6 | | -#include <vector> |
7 | | -#include <ranges> |
8 | | - |
9 | 6 | namespace cp_algo::graph { |
10 | 7 | struct heavy_light { |
11 | 8 | big_vector<node_index> size, in, up, par; |
@@ -55,15 +52,57 @@ namespace cp_algo::graph { |
55 | 52 | } |
56 | 53 | } |
57 | 54 | } |
58 | | - node_index lca(node_index a, node_index b) { |
| 55 | + enum lca_mode { without_distances, with_distances }; |
| 56 | + template<lca_mode mode = without_distances> |
| 57 | + auto lca(node_index a, node_index b) { |
| 58 | + int dista = 0, distb = 0; |
59 | 59 | while (up[a] != up[b]) { |
60 | | - if (in[a] < in[b]) { |
| 60 | + if (in[up[a]] < in[up[b]]) { |
| 61 | + if constexpr (mode == with_distances) distb += in[b] - in[up[b]] + 1; |
61 | 62 | b = par[up[b]]; |
62 | 63 | } else { |
| 64 | + if constexpr (mode == with_distances) dista += in[a] - in[up[a]] + 1; |
63 | 65 | a = par[up[a]]; |
64 | 66 | } |
65 | 67 | } |
66 | | - return in[a] < in[b] ? a : b; |
| 68 | + node_index c = in[a] < in[b] ? a : b; |
| 69 | + if constexpr (mode == with_distances) { |
| 70 | + return std::tuple{c, dista + in[a] - in[c], distb + in[b] - in[c]}; |
| 71 | + } else { |
| 72 | + return c; |
| 73 | + } |
| 74 | + } |
| 75 | + big_vector<node_index> rin; |
| 76 | + void compute_rin() { |
| 77 | + if (empty(rin)) { |
| 78 | + rin.resize(std::size(in)); |
| 79 | + for (auto [v, inv]: in | std::views::enumerate) { |
| 80 | + rin[inv] = node_index(v); |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + node_index jump_up(node_index v, int steps) { |
| 85 | + compute_rin(); |
| 86 | + while (steps > 0) { |
| 87 | + int path_dist = in[v] - in[up[v]]; |
| 88 | + if (steps <= path_dist) { |
| 89 | + return rin[in[v] - steps]; |
| 90 | + } |
| 91 | + steps -= path_dist + 1; |
| 92 | + v = par[up[v]]; |
| 93 | + } |
| 94 | + return v; |
| 95 | + } |
| 96 | + std::optional<node_index> jump(node_index from, node_index to, int steps) { |
| 97 | + compute_rin(); |
| 98 | + auto [l, dist_from, dist_to] = lca<with_distances>(from, to); |
| 99 | + auto dist = dist_from + dist_to; |
| 100 | + if (steps > dist) return std::nullopt; |
| 101 | + if (steps <= dist_from) { |
| 102 | + return jump_up(from, steps); |
| 103 | + } else { |
| 104 | + return jump_up(to, dist - steps); |
| 105 | + } |
67 | 106 | } |
68 | 107 | }; |
69 | 108 | } |
|
0 commit comments