Four tree problems rated 2,000 to 2,200 with many queries and changing values. The move: flatten the tree into an array, so that a subtree is one range and a path is a few ranges.
This tent holds four problems rated 2,000 to 2,200. All of them have one tree and up to 10^5 questions. They ask for the lowest account above a range of ids and the error total under a service. They also ask for the cheapest stop for three riders and the peak value on a route.
The first solution walks the tree for each question. It is correct, and the walk can be as long as the tree.
| Problem | The literal route | Its size at the limits |
|---|---|---|
| The lowest account that owns a range of ids | climb from each id | 3.6 × 10^9 steps |
| Error totals under a service, with changes | add up the subtree for each question | 10^10 steps |
| The cheapest meeting stop for three riders | climb for each of the three pairs | 7.5 × 10^9 steps |
| The peak congestion on a route | walk the route for each question | 1.6 × 10^9 steps |
Each tree here can be a path of 10^5 nodes, so a walk is long and recursion is not safe.
Exercise · Predict the output: Subtree totals from an Euler tour. Node 0 is the root, and parents[v] is the parent of v. A search enters the children in increasing order and numbers the nodes in that order, as tin. A subtree is then the range of tin from its first node to its last, and prefix holds running totals. What does this print: the totals under node 1 and under node 2?
parents = [-1, 0, 0, 1, 1, 2]
values = [1, 2, 3, 4, 5, 6]
n = 6
children = [[] for _ in range(n)]
for v in range(1, n):
children[parents[v]].append(v)
tin = [0] * n
size = [1] * n
order = []
def dfs(v):
tin[v] = len(order)
order.append(v)
for c in children[v]:
dfs(c)
size[v] += size[c]
dfs(0)
prefix = [0]
for v in order:
prefix.append(prefix[-1] + values[v])
def subtree(v):
return prefix[tin[v] + size[v]] - prefix[tin[v]]
print(subtree(1), subtree(2))Number the nodes in the order a depth-first search enters them. Every subtree is then a block of consecutive numbers: it starts at tin[v] and holds size[v] nodes.
Number the nodes in the order a search enters them, so that every subtree is one range of an array. Then use a structure on arrays for the question.
A subtree total becomes a range sum, and a Fenwick tree handles the changes. The tour also holds the lowest common ancestor. Write down the depth of every node each time the tour passes it. The lowest common ancestor of two nodes is the shallowest node between their first visits, which is a range minimum.
The distance follows from the depths: depth[a] + depth[b] - 2 × depth[c]. For a weighted tree, use the distance from the root in place of the depth. Three riders meet at the stop with the least total travel, and that total is half the sum of the three pairwise distances.
Number the nodes in the order a search enters them, and every subtree becomes a range: a subtree total is a range sum.
Exercise · Find the bug: The subtree that loses its last node. prefix[i] holds the total of the first i nodes in tour order. tin[v] is where the tour enters v. size[v] counts the nodes under v, v included. This returns the total under v. Which line is wrong?
def subtree_total(prefix, tin, size, v):
return prefix[tin[v] + size[v] - 1] - prefix[tin[v]]The Academy lessons Lowest common ancestor and Tree recursion climbed and recursed, and Prefix sums answered ranges. Graph traversal gave you the order of a search. The camp before this one added Binary lifting and sparse tables and Segment trees for contests. This tent flattens the tree so that those array tools apply.
Heavy light decomposition handles routes. Each node's heavy child is the child with the largest subtree. Number the heavy child first, so that every chain of heavy children is one range.
A route between two nodes then crosses at most about 16 chains for 40,000 nodes, because each light edge at least halves the subtree size. A query is a few ranges of a segment tree.
The distance formula has a classic slip: forgetting that the shared part of the route is counted twice.
The distance is both depths minus twice the ancestor's depth, because the route to the ancestor is counted by both depths.
Exercise · Break it: The shared part of the route. parents[v] is the parent of node v, with parents[0] = -1, and every parent has a smaller number than its child. This returns the number of links between nodes a and b. It adds the depths and subtracts the depth of their lowest common ancestor. Find an input where it is wrong.
def tree_distance(parents, a, b):
n = len(parents)
depth = [0] * n
for v in range(1, n):
depth[v] = depth[parents[v]] + 1
x, y = a, b
while x != y:
if depth[x] >= depth[y]:
x = parents[x]
else:
y = parents[y]
return depth[a] + depth[b] - depth[x]| Limit | What it tells you |
|---|---|
| a tree of 10^5 nodes | a path is possible: number the nodes without recursion |
| 10^5 queries and changes | a Fenwick tree over the tour: about 17 steps each |
| node values up to 10^9 on 10^5 nodes | totals reach 10^14: 64-bit integers |
| weighted roads up to 10^6 on 5 × 10^4 nodes | a distance reaches 5 × 10^10: 64-bit integers |
| every parent below its child | sizes come from one backward loop, and tour numbers from a running offset |
The full treatment is in Fast I/O and stress testing. The input lists the parents of nodes 2 to n, then the n values, then one row of three numbers per operation. A row holds a kind (0 adds to a value, 1 asks a subtree total), a node, and an amount. The tour numbers need no recursion, because each parent comes before its child.
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
parent = [0, 0] + [int(x) for x in data[1:n]]
value = [0] + [int(x) for x in data[n:2 * n]]
size = [1] * (n + 1)
for v in range(n, 1, -1):
size[parent[v]] += size[v]
tin = [0] * (n + 1)
nxt = [0] * (n + 1)
tin[1], nxt[1] = 1, 2
for v in range(2, n + 1):
p = parent[v]
tin[v] = nxt[p]
nxt[p] += size[v]
nxt[v] = tin[v] + 1
tree = [0] * (n + 2)
def add(i, x):
while i <= n:
tree[i] += x
i += i & -i
def total(i):
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
for v in range(1, n + 1):
add(tin[v], value[v])
q = int(data[2 * n])
out = []
at = 2 * n + 1
for _ in range(q):
kind, v, x = int(data[at]), int(data[at + 1]), int(data[at + 2])
at += 3
if kind == 0:
add(tin[v], x)
else:
out.append(total(tin[v] + size[v] - 1) - total(tin[v] - 1))
sys.stdout.write("\n".join(map(str, out)) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
static long[] tree;
static int n;
static void add(int i, long x) {
for (; i <= n; i += i & -i) tree[i] += x;
}
static long total(int i) {
long s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
n = (int) in.nval;
int[] parent = new int[n + 1];
for (int v = 2; v <= n; v++) {
in.nextToken();
parent[v] = (int) in.nval;
}
long[] value = new long[n + 1];
for (int v = 1; v <= n; v++) {
in.nextToken();
value[v] = (long) in.nval;
}
int[] size = new int[n + 1];
Arrays.fill(size, 1);
for (int v = n; v >= 2; v--) size[parent[v]] += size[v];
int[] tin = new int[n + 1], nxt = new int[n + 1];
tin[1] = 1;
nxt[1] = 2;
for (int v = 2; v <= n; v++) {
int p = parent[v];
tin[v] = nxt[p];
nxt[p] += size[v];
nxt[v] = tin[v] + 1;
}
tree = new long[n + 2];
for (int v = 1; v <= n; v++) add(tin[v], value[v]);
in.nextToken();
int q = (int) in.nval;
StringBuilder out = new StringBuilder();
for (int t = 0; t < q; t++) {
in.nextToken();
int kind = (int) in.nval;
in.nextToken();
int v = (int) in.nval;
in.nextToken();
long x = (long) in.nval;
if (kind == 0) add(tin[v], x);
else out.append(total(tin[v] + size[v] - 1) - total(tin[v] - 1)).append("\n");
}
System.out.print(out);
}
}#include <iostream>
#include <vector>
using namespace std;
int n;
vector<long long> tree;
void add(int i, long long x) {
for (; i <= n; i += i & -i) tree[i] += x;
}
long long total(int i) {
long long s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
vector<int> parent(n + 1, 0);
for (int v = 2; v <= n; v++) cin >> parent[v];
vector<long long> value(n + 1, 0);
for (int v = 1; v <= n; v++) cin >> value[v];
vector<int> size(n + 1, 1);
for (int v = n; v >= 2; v--) size[parent[v]] += size[v];
vector<int> tin(n + 1, 0), nxt(n + 1, 0);
tin[1] = 1;
nxt[1] = 2;
for (int v = 2; v <= n; v++) {
int p = parent[v];
tin[v] = nxt[p];
nxt[p] += size[v];
nxt[v] = tin[v] + 1;
}
tree.assign(n + 2, 0);
for (int v = 1; v <= n; v++) add(tin[v], value[v]);
int q;
cin >> q;
for (int t = 0; t < q; t++) {
int kind, v;
long long x;
cin >> kind >> v >> x;
if (kind == 0) add(tin[v], x);
else cout << total(tin[v] + size[v] - 1) - total(tin[v] - 1) << "\n";
}
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
const parent = [0, 0];
for (let v = 2; v <= n; v++) parent.push(data[v - 1]);
const value = [0];
for (let v = 1; v <= n; v++) value.push(data[n + v - 1]);
const size = new Array(n + 1).fill(1);
for (let v = n; v >= 2; v--) size[parent[v]] += size[v];
const tin = new Array(n + 1).fill(0);
const nxt = new Array(n + 1).fill(0);
tin[1] = 1;
nxt[1] = 2;
for (let v = 2; v <= n; v++) {
const p = parent[v];
tin[v] = nxt[p];
nxt[p] += size[v];
nxt[v] = tin[v] + 1;
}
const tree = new Array(n + 2).fill(0);
function add(i, x) {
for (; i <= n; i += i & -i) tree[i] += x;
}
function total(i) {
let s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
for (let v = 1; v <= n; v++) add(tin[v], value[v]);
const q = data[2 * n];
const out = [];
let at = 2 * n + 1;
for (let t = 0; t < q; t++) {
const kind = data[at], v = data[at + 1], x = data[at + 2];
at += 3;
if (kind === 0) add(tin[v], x);
else out.push(total(tin[v] + size[v] - 1) - total(tin[v] - 1));
}
process.stdout.write(out.join("\n") + "\n");On the sample with 6 nodes, the parents 1 1 2 2 3 and the values 1 2 3 4 5 6, take the four operations 1 2 0, 0 4 10, 1 2 0 and 1 1 0. All four programs print 11, 21 and 31, one per line.
The slow twin keeps the values in a list and, for each question, climbs from every node to see whether it lies under the asked node. It shares no tour numbering with the fast code.
import random
from fast import subtree_totals
from slow import subtree_totals as slow_totals
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 9)
parents = [-1] + [rng.randrange(v) for v in range(1, n)]
values = [rng.randint(0, 9) for _ in range(n)]
ops = [[rng.randint(0, 1), rng.randrange(n), rng.randint(0, 9)] for _ in range(8)]
if subtree_totals(parents, values, ops) != slow_totals(parents, values, ops):
print("different at seed", seed)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Read the end of the range one position short, and seed 0 already fails.
At 2,000 to 2,200 the flattening is known, and the work is the bookkeeping: the range ends, the 64-bit totals, and the tree that is a path. Write the array you flatten into, and the structure on it, in one line before you code. Aim for about 50 minutes a problem, and keep 10 for the stress test on trees of up to 9 nodes.
The first is the lowest common ancestor from the tour. The two rated 2,100 use the tour for totals and for distances. The last, rated 2,200, takes routes with heavy light decomposition.
For each problem, write the array you flatten into and the structure on it, in one line. Then write the slow twin that walks the tree, and stress test on up to 9 nodes.
Checkpoint · LCA and tree queries
Q1/5 Why does numbering the nodes in the order a search enters them help?
Answer: B
The subtree of v is the range from tin[v] to tin[v] + size[v] - 1. A subtree total is then a range sum.
Q2/5 For the parents -1, 0, 0, 1, 1, 2 and the values 1 to 6, what is the total under node 1?
Answer: B
The subtree of node 1 holds the nodes 1, 3 and 4, with the values 2, 4 and 5: 11. The value 6 comes from dropping the last node.
Q3/5 For parents of -1, 0, 1, 1, what is the distance between nodes 2 and 3?
Answer: B
Each is 2 links from the root, and their lowest common ancestor is node 1, at depth 1: 2 + 2 - 2 × 1 = 2. Subtracting only once gives 3.
Q4/5 Why does a route cross only a few chains in heavy light decomposition?
Answer: B
Heavy children are numbered together, so each chain is one range. A route has at most about log2 of n light edges, so it is a few ranges.
Q5/5 What does a rating of 2,000 to 2,200 usually ask of you?
Answer: B
The tools are known. Wrong answers come from a range that ends one short, a missing factor of 2, or a recursion that overflows on a path.
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.