Binary Jumping
Authors: Benjamin Qi, Neo Wang
Introduces the problems of finding level ancestors in a tree and computing the lowest common ancestors.
Binary Jumping
Focus Problem – read through this problem before continuing!
Tutorial
Resources | |||
---|---|---|---|
CPH | |||
AryanshS | |||
SecondThread |
Pro Tip
Binary jumping is more commonly referred to as "binary lifting."
Solution
To solve this problem, we can use a standard binary lifting implementation where jmp(int x, int d)
corresponds to the -th ancestor of .
In our jmp(int x, int d)
if our final value of is , then such a node does not exist and we can simply return . This is because the lowest number a node can be is (the root of the tree).
In our implementation, we test if we jump in powers of two by using the operator. If the th bit on the right is toggled, then we jump. For example, a jump of would correspond to the binary number . We would jump 3 times on bits (in that order) counting from the right.
Illustration of the jump method
To calculate the rows required for the int up[MS][MX]
array, use the formula which in our case simplifies to .
Pro Tip
It never hurts to add additional rows - or columns, depending on your implementation - (as long as it's reasonable)!
C++
#include <bits/stdc++.h>using namespace std;#define FOR(i, a, b) for(int i = (a); i < (b); i++)#define FORE(i, a, b) for(int i = (a); i <= (b); i++)#define F0R(i, a) for(int i = 0; i < (a); i++)#define trav(a, x) for (auto& a : x)int N, Q;
Problems
Status | Source | Problem Name | Difficulty | Tags | Solution | URL |
---|---|---|---|---|---|---|
CSES | Easy | Show TagsBinary Jumping | ||||
CSES | Normal | Show TagsFunc Graph | ||||
POI | Normal | |||||
CF | Normal | Check CF | ||||
Baltic OI | Normal | External Sol | ||||
Baltic OI | Normal | |||||
Plat | Hard | Show TagsBinary Jumping | External Sol | |||
Baltic OI | Very Hard |
Lowest Common Ancestor
Focus Problem – read through this problem before continuing!
Focus Problem – read through this problem before continuing!
Tutorial
Resources | |||
---|---|---|---|
CPH | |||
cp-algo |
- CF: queries and memory
- Wikipedia: queries and preprocessing time
- though explanation is not the greatest
Implementation
Resources | |||
---|---|---|---|
Benq |
This section is not complete.
Problems
USACO
Status | Source | Problem Name | Difficulty | Tags | Solution | URL |
---|---|---|---|---|---|---|
Plat | Easy | Show TagsLCA | External Sol | |||
Plat | Normal | Show TagsLCA | External Sol | |||
Plat | Hard | Show TagsLCA | External Sol | |||
Plat | Hard | Show TagsDiameter | External Sol | |||
Plat | Hard | Show TagsLCA | External Sol | |||
Plat | Very Hard | Show TagsLCA | External Sol |
General
This section is not complete.
figure out a better way to order these, difficulties aren't rlly accurate
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!