Four problems rated 1,800 to 1,900 on jumps up a tree and minimums over fixed ranges. The move: store the answer for every power-of-two length, then build any length from a few of them.
This tent holds four problems rated 1,800 to 1,900. Two ask for a jump of k steps up a tree: the k-th reply above a message, and the meeting point of friends on a tree of junctions. Two ask about ranges that never change: the swing of a window of a playlist, and the live part of a chain.
The first solution walks or scans, one step at a time. It is correct and, for 10^5 queries, far too slow.
| Problem | The literal route | Its size at the limits |
|---|---|---|
| Jump k replies up a thread | follow the reply link k times | 10^10 steps |
| Popularity swing in a looping playlist | scan each window | 10^10 steps |
| The live part of a reply chain | walk the chain for each question | 10^10 steps |
| Where three friends should meet | climb to the common ancestor, three times | 1.2 × 10^10 steps |
With a table of jumps, each query takes at most 17 steps, because 2^17 is 131,072, above the largest depth.
Exercise · Predict the output: Jumps from the bits of k. The table up[j][v] holds the node reached from v by 2^j steps up, and the root points at itself. The parents are 0, 0, 1, 1, 2, 4 for the nodes 0 to 5. This jumps by the binary digits of k. What does it print?
p = [0, 0, 1, 1, 2, 4]
LOG = 3
up = [p[:]]
for j in range(1, LOG):
up.append([up[j - 1][up[j - 1][v]] for v in range(6)])
def jump(v, k):
for j in range(LOG):
if k >> j & 1:
v = up[j][v]
return v
print(jump(5, 3), jump(5, 4), jump(3, 5))A jump of k steps is a jump of 8, plus a jump of 4, plus a jump of 1, for k = 13. So store the jump of every power of two, for every node. Then any k is at most 17 table reads.
Store the answer for every power-of-two length. Build any length from a few of them: the bits of k for a jump, and two overlapping blocks for a range minimum.
The table fills itself. A jump of 2^j steps is two jumps of 2^(j-1) steps, so up[j][v] = up[j - 1][up[j - 1][v]]. You fill it level by level, so the order of the node ids does not matter. A reply may have a smaller id than the message it answers.
A minimum over a range works the same way, with one gift. A minimum counts a value twice without changing, so two overlapping blocks of length 2^k cover any range, with k = floor(log2(length)). The query is two reads.
The tree problems use the table twice. Lifting a node to the depth of another is a jump by the difference. Lifting both nodes together, from the longest jump to the shortest, stops one step below their lowest common ancestor.
A jump of k steps uses the binary digits of k: each set bit is one jump from the table of power-of-two jumps.
Exercise · Find the bug: The block that starts too early. This returns the lowest score of the slots lo to hi, both included. It builds the table of block minimums, then reads two overlapping blocks. Which line is wrong?
def lowest_score(values, lo, hi):
n = len(values)
table = [values[:]]
k = 1
while (1 << k) <= n:
prev = table[-1]
half = 1 << (k - 1)
table.append([min(prev[i], prev[i + half]) for i in range(n - (1 << k) + 1)])
k += 1
k = (hi - lo + 1).bit_length() - 1
second = hi - (1 << k)
return min(table[k][lo], table[k][second])The Academy lesson Lowest common ancestor climbed one step at a time, and Tree recursion gave you the depth of every node. Prefix sums answered ranges from a table, and First-true template searched on a yes or no answer. This tent combines them: a table of jumps, searched from the longest jump down.
The search is the third problem. Times grow down a reply chain, so the posts with a time of at least the cutoff form a stretch at the end of the chain. From the post, take the longest jump whose target is still recent enough, then the next longest, and so on. That is the binary search of the Academy, on a path.
The trap is the end of the tree. A reply thread has a root, and a jump may ask for more steps than the thread has.
A root that points at itself makes a jump past the end return the root; use a sentinel and answer minus one.
Exercise · Break it: The jump that runs out of thread. parents[i] is the message that message i answers, or -1 for the start of a thread. This returns the message reached after k steps up from v, or -1 when the thread ends first. The root points at itself in the table. Find an input where it is wrong.
def jump_up(parents, v, k):
n = len(parents)
LOG = 5
up = [[parents[i] if parents[i] != -1 else i for i in range(n)]]
for j in range(1, LOG):
up.append([up[j - 1][up[j - 1][i]] for i in range(n)])
for j in range(LOG):
if k >> j & 1:
v = up[j][v]
return v| Limit | What it tells you |
|---|---|
| depth up to 10^5 | 17 levels: 2^17 = 131,072. A table of 17 × 10^5 = 1.7 × 10^6 entries |
| k up to 10^9 | if k is 2^17 or more, the answer is -1 at once, since no thread is that deep |
| ids in any order | fill the table by levels, and compute depths with a queue, not by recursion |
| a window that wraps round | repeat the list twice, so a window never wraps |
| 10^5 queries | read the input once, and print the answers once |
The full treatment is in Fast I/O and stress testing. The table has a sentinel node n that points at itself, so a jump past the root lands on n, and n is printed as -1.
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
LOG = 17
up = [[n] * (n + 1) for _ in range(LOG)]
for v in range(n):
p = int(data[1 + v])
up[0][v] = p if p != -1 else n
for j in range(1, LOG):
prev, cur = up[j - 1], up[j]
for v in range(n + 1):
cur[v] = prev[prev[v]]
q = int(data[1 + n])
out = []
for i in range(q):
v, k = int(data[2 + n + 2 * i]), int(data[3 + n + 2 * i])
if k >= (1 << LOG):
out.append(-1)
continue
for j in range(LOG):
if k >> j & 1:
v = up[j][v]
out.append(v if v != n else -1)
sys.stdout.write("\n".join(map(str, out)) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
int LOG = 17;
int[][] up = new int[LOG][n + 1];
Arrays.fill(up[0], n);
for (int v = 0; v < n; v++) {
in.nextToken();
int p = (int) in.nval;
up[0][v] = p != -1 ? p : n;
}
for (int j = 1; j < LOG; j++)
for (int v = 0; v <= n; v++) up[j][v] = up[j - 1][up[j - 1][v]];
in.nextToken();
int q = (int) in.nval;
StringBuilder out = new StringBuilder();
for (int i = 0; i < q; i++) {
in.nextToken();
int v = (int) in.nval;
in.nextToken();
int k = (int) in.nval;
if (k >= (1 << LOG)) {
out.append(-1).append("\n");
continue;
}
for (int j = 0; j < LOG; j++) if ((k >> j & 1) == 1) v = up[j][v];
out.append(v != n ? v : -1).append("\n");
}
System.out.print(out);
}
}#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
const int LOG = 17;
vector<vector<int>> up(LOG, vector<int>(n + 1, n));
for (int v = 0; v < n; v++) {
int p;
cin >> p;
up[0][v] = p != -1 ? p : n;
}
for (int j = 1; j < LOG; j++)
for (int v = 0; v <= n; v++) up[j][v] = up[j - 1][up[j - 1][v]];
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int v, k;
cin >> v >> k;
if (k >= (1 << LOG)) {
cout << -1 << "\n";
continue;
}
for (int j = 0; j < LOG; j++) if (k >> j & 1) v = up[j][v];
cout << (v != n ? v : -1) << "\n";
}
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
const LOG = 17;
const up = [];
for (let j = 0; j < LOG; j++) up.push(new Array(n + 1).fill(n));
for (let v = 0; v < n; v++) up[0][v] = data[1 + v] !== -1 ? data[1 + v] : n;
for (let j = 1; j < LOG; j++)
for (let v = 0; v <= n; v++) up[j][v] = up[j - 1][up[j - 1][v]];
const q = data[1 + n];
const out = [];
for (let i = 0; i < q; i++) {
let v = data[2 + n + 2 * i];
const k = data[3 + n + 2 * i];
if (k >= (1 << LOG)) {
out.push(-1);
continue;
}
for (let j = 0; j < LOG; j++) if (k >> j & 1) v = up[j][v];
out.push(v !== n ? v : -1);
}
process.stdout.write(out.join("\n") + "\n");On the sample with 6 messages, the parents -1 0 0 1 1 3 and the three questions 5 3, 4 1 and 3 5, all four programs print 0, 1 and -1, one per line.
The slow twin follows the reply link k times, one step at a time. It cannot share a table mistake with the fast code.
import random
from fast import jump_up
from slow import jump_up as slow_jump
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 10)
order = list(range(n))
rng.shuffle(order)
parents = [-1] * n
for i in range(1, n):
parents[order[i]] = order[rng.randrange(i)]
queries = [[rng.randrange(n), rng.randint(0, n + 1)] for _ in range(8)]
if jump_up(parents, queries) != slow_jump(parents, queries):
print("different at", parents, queries)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Read the second block of a sparse table one slot early, and the first random input fails. For the scores 6, 0, 4, 8, 7, 6, 4 and the window 3 to 5 it gives 7 instead of 6.
At 1,800 to 2,000 the table is a known tool, and the work is the edge: the sentinel, the wrap, the order of the jumps. Write the table, its size and the edge case in one line before you code. Aim for about 40 minutes a problem, and keep 10 for the stress test.
The first two are the two tables: jumps up a tree and blocks of a list. The two rated 1,900 use the jump table more cleverly: a search along a path, and lifting two nodes together.
For each problem, write the table, its size and one edge case in one line. Then write the slow twin that walks or scans, and stress test on up to 10 nodes.
Checkpoint · Binary lifting and sparse tables
Q1/5 How do you jump 13 steps up a tree with a table of power-of-two jumps?
Answer: B
13 is 1101 in binary. The table has a jump for every power of two, so a jump of any k takes at most 17 reads for depths below 2^17.
Q2/5 How many entries does the jump table have for 10^5 nodes and a depth below 131,072?
Answer: C
There are 17 levels of 10^5 entries each: 1.7 × 10^6. Each entry is one parent of a parent, filled level by level.
Q3/5 Why do two overlapping blocks give the right range minimum?
Answer: B
With k = floor(log2(length)), the blocks from lo and from hi - 2^k + 1 cover the range. This does not work for sums, which would count the overlap twice.
Q4/5 A root points at itself in the table. For the chain 3, 2, 1, 0 (0 is the root), what does a jump of 4 steps from node 3 return?
Answer: B
The jump stays at the root. The correct answer is -1, so the table needs a sentinel node and the answer -1 when a jump ends on it.
Q5/5 What does a rating of 1,800 to 2,000 usually ask of you?
Answer: B
The tables are standard. Wrong answers come from the edge: a jump past the root, a second block that starts early, or a window that wraps.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.