From 9facd3655e2b86799699a6fdbd566cb4b2a7fb1c Mon Sep 17 00:00:00 2001 From: Paul Jungeblut Date: Fri, 22 Dec 2017 12:49:35 +0100 Subject: Adding new code for sparse table implementation and LCA. --- graph/LCA.cpp | 21 --------------------- graph/graph.tex | 2 +- graph/lca.cpp | 28 ++++++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 22 deletions(-) delete mode 100644 graph/LCA.cpp create mode 100644 graph/lca.cpp (limited to 'graph') diff --git a/graph/LCA.cpp b/graph/LCA.cpp deleted file mode 100644 index c79cc5c..0000000 --- a/graph/LCA.cpp +++ /dev/null @@ -1,21 +0,0 @@ -vector visited(2*MAX_N), first(MAX_N, 2*MAX_N), depth(2*MAX_N); -vector> graph(MAX_N); - -// Funktioniert nur mit von der Wurzel weggerichteten Kanten. -// Falls ungerichtete Kanten, visited-check einführen. -void initLCA(int gi, int d, int &c) { // Laufzeit: O(n) - visited[c] = gi, depth[c] = d, first[gi] = min(c, first[gi]), c++; - for(int gn : graph[gi]) { - initLCA(gn, d+1, c); - visited[c] = gi, depth[c] = d, c++; -}} - -int getLCA(int a, int b) { // Laufzeit: O(1) - return visited[queryRMQ( - min(first[a], first[b]), max(first[a], first[b]))]; -} - -// Benutzung: -int c = 0; -initLCA(0, 0, c); -initRMQ(); // Ersetze das data im RMQ-Code von oben durch depth. diff --git a/graph/graph.tex b/graph/graph.tex index 7b901f9..37356f6 100644 --- a/graph/graph.tex +++ b/graph/graph.tex @@ -58,7 +58,7 @@ VISIT(v): \lstinputlisting{graph/euler.cpp} \subsection{Lowest Common Ancestor} -\lstinputlisting{graph/LCA.cpp} +\lstinputlisting{graph/lca.cpp} \subsection{Max-Flow} diff --git a/graph/lca.cpp b/graph/lca.cpp new file mode 100644 index 0000000..d6548e9 --- /dev/null +++ b/graph/lca.cpp @@ -0,0 +1,28 @@ +struct LCA { + vector depth, visited, first; + int idx; + SparseTable st; + + void init(vector> &g, int root) { // Laufzeit: O(|V|) + depth.assign(2 * g.size(), 0); + visited.assign(2 * g.size(), -1); + first.assign(g.size(), 2 * g.size()); + idx = 0; + visit(g, root, 0); + st.init(&depth); + } + + void visit(vector> &g, int v, int d) { + visited[idx] = v, depth[idx] = d, first[v] = min(idx, first[v]), idx++; + + for (int w : g[v]) { + if (first[w] == 2 * (int)g.size()) { + visit(g, w, d + 1); + visited[idx] = v, depth[idx] = d, idx++; + }}} + + int getLCA(int a, int b) { // Laufzeit: O(1) + if (first[a] > first[b]) swap(a, b); + return visited[st.queryIdempotent(first[a], first[b])]; + } +}; -- cgit v1.2.3