PrevNext

LCA

Focus Problem – try your best to solve this problem before continuing!

View Internal Solution

Focus Problem – try your best to solve this problem before continuing!

Tutorial

Implementation

Resources
Benq

import java.io.*;
import java.util.*;
public class LCA {
public static int[] euler_tour, tin;
public static int timer, size, N;
public static ArrayList<Integer> g[];
// Segtree code
public static final int maxsize = (int)1e7; // limit for array size

Sparse Tables

The above code does O(N)\mathcal{O}(N) time preprocessing and allows LCA queries in O(logN)\mathcal{O}(\log N) time. If we replace the segment tree that computes minimums with a sparse table, then we do O(NlogN)\mathcal{O}(N\log N) time preprocessing and query in O(1)\mathcal{O}(1) time.

Focus Problem – try your best to solve this problem before continuing!

The following is an example implementation of a sparse table and code that answers LCA queries. Build time is O(NlogN)\mathcal{O}(N\log N), and queries are O(1)\mathcal{O}(1).

#include <bits/stdc++.h>
using namespace std;
template <typename T> class SparseTable {
private:
int n, log2dist;
vector<vector<T>> st;
public:
SparseTable(const vector<T> &v) {

Resources

Optional: Faster Preprocessing

From CPH:

There are also more sophisticated techniques where the preprocessing time is only O(N)\mathcal{O}(N), but such algorithms are not needed in competitive programming.

Ex. the following:

Implementation

Resources
Benq

Problems

StatusSourceProblem NameDifficultyTags
GoldMedium
Show TagsEuler Tour, LCA, PURS
GoldMedium
Show TagsEuler Tour, LCA
ACMedium
Show TagsEuler Tour, LCA, PURS
DMOPCHard
Show TagsEuler Tour, LCA, PURS

Module Progress:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

PrevNext