LCA
Focus Problem – try your best to solve this problem before continuing!
View Internal SolutionFocus Problem – try your best to solve this problem before continuing!
Tutorial
| Resources | |||||
|---|---|---|---|---|---|
| CPH | |||||
| cp-algo | |||||
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 codepublic static final int maxsize = (int)1e7; // limit for array size
Sparse Tables
The above code does time preprocessing and allows LCA queries in time. If we replace the segment tree that computes minimums with a sparse table, then we do time preprocessing and query in 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 , and queries are .
#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
| Resources | |||||
|---|---|---|---|---|---|
| CPH | diagrams | ||||
| PAPS | code | ||||
| cp-algo | |||||
From CPH:
There are also more sophisticated techniques where the preprocessing time is only , but such algorithms are not needed in competitive programming.
Ex. the following:
Implementation
| Resources | |||||
|---|---|---|---|---|---|
| Benq | |||||
Problems
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| Gold | Medium | Show TagsEuler Tour, LCA, PURS | ||||
| Gold | Medium | Show TagsEuler Tour, LCA | ||||
| AC | Medium | Show TagsEuler Tour, LCA, PURS | ||||
| DMOPC | Hard | 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!