summaryrefslogtreecommitdiff
path: root/graph/LCA_sparse.cpp
diff options
context:
space:
mode:
authormzuenni <michi.zuendorf@gmail.com>2022-06-27 17:19:28 +0200
committermzuenni <michi.zuendorf@gmail.com>2022-06-27 17:19:28 +0200
commit5ab8a5088b729a9953b8dff1b2a985dc8fb2098b (patch)
treeed40d6936c0e9eee40ba62751cbf99ecddbaddc2 /graph/LCA_sparse.cpp
parentadabbad9c51cf7cd3874bfde8eac1fbcf84fec10 (diff)
updated tcr
Diffstat (limited to 'graph/LCA_sparse.cpp')
-rw-r--r--graph/LCA_sparse.cpp32
1 files changed, 32 insertions, 0 deletions
diff --git a/graph/LCA_sparse.cpp b/graph/LCA_sparse.cpp
new file mode 100644
index 0000000..2a38528
--- /dev/null
+++ b/graph/LCA_sparse.cpp
@@ -0,0 +1,32 @@
+struct LCA {
+ vector<ll> depth;
+ vector<int> visited, first;
+ int idx;
+ SparseTable st; //sparse table von oben
+
+ void init(vector<vector<int>>& g, int root) {
+ depth.assign(2 * sz(g), 0);
+ visited.assign(2 * sz(g), -1);
+ first.assign(sz(g), 2 * sz(g));
+ idx = 0;
+ visit(g, root);
+ st.init(&depth);
+ }
+
+ void visit(vector<vector<int>>& g, int v, ll d=0, int p=-1) {
+ visited[idx] = v, depth[idx] = d;
+ first[v] = min(idx, first[v]), idx++;
+
+ for (int w : g[v]) {
+ if (first[w] == 2 * sz(g)) {
+ visit(g, w, d + 1, v);
+ visited[idx] = v, depth[idx] = d, idx++;
+ }}}
+
+ int getLCA(int a, int b) {
+ if (first[a] > first[b]) swap(a, b);
+ return visited[st.queryIdempotent(first[a], first[b] + 1)];
+ }
+
+ ll getDepth(int a) {eturn depth[first[a]];}
+};