From 5ab8a5088b729a9953b8dff1b2a985dc8fb2098b Mon Sep 17 00:00:00 2001 From: mzuenni Date: Mon, 27 Jun 2022 17:19:28 +0200 Subject: updated tcr --- graph/LCA_sparse.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 graph/LCA_sparse.cpp (limited to 'graph/LCA_sparse.cpp') 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 depth; + vector visited, first; + int idx; + SparseTable st; //sparse table von oben + + void init(vector>& 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>& 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]];} +}; -- cgit v1.2.3