Five tree problems rated 1,600 to 1,800 where an answer is needed for every node. The move: order the nodes once, then sweep the order backwards for totals from below and forwards for values from above.
This tent holds five problems rated 1,600 to 1,800, all on trees with up to 10^5 nodes. The Academy taught you to answer one question about a tree with a recursive walk. Here the question is asked at every node, for every pair, or for every possible root.
The walk per question is correct and too slow, and a deep tree adds a second problem: the recursion itself.
| Problem | The walk per question | Its size at the limits |
|---|---|---|
| Rolled-up spend of every team | add up the branch of each team | 5,000,050,000 steps on a chain of 10^5 |
| End categories under every category | count the leaves below each one | 5,000,050,000 steps on a chain of 10^5 |
| Slowest path between two services | try every pair | 5 × 10^9 pairs |
| Trip lengths on a tree of roads | follow the path for each trip | 2.5 × 10^9 steps |
| Where to place the depot | price every possible root | 10^10 steps |
Python stops a recursion at 1,000 nested calls by default, and a chain of 10^5 nodes is 100 times deeper. So the first change is to leave recursion out.
Exercise · Predict the output: Leaves under every category. A category count walks the categories from the last to the first. A category that has received nothing counts as 1, then passes its count to its parent. What does this print?
parents = [-1, 0, 0, 1, 1, 2]
leaves = [0] * 6
for v in range(5, -1, -1):
if leaves[v] == 0:
leaves[v] = 1
if v > 0:
leaves[parents[v]] += leaves[v]
print(*leaves)List the nodes from the root outwards, so that every node comes after its parent. A queue does it in one pass, and so does the input itself when every parent has a smaller number than its child.
Sweep backwards for a value that comes from below, such as a total. Sweep forwards for a value that comes from above, such as a distance.
Backwards works because a node is reached only after all its children, so its value is complete when it passes it up. Forwards works for the opposite reason: a node is reached after its parent, so its parent's value is ready.
Three of the five problems are exactly this. The spend and the leaf count are backward sweeps, and the distance of every town from the root is a forward sweep.
The diameter needs two forward sweeps. The farthest node from any start is one end of the longest route, and the farthest node from that end is the other.
Walk the order backwards and add each team's total to its boss; every team is complete when it is reached.
Exercise · Find the bug: Totals that are not complete. This returns the total spend of every team's branch. Every team's boss has a smaller number than the team. Which line is wrong?
def subtree_totals(parents, spend):
n = len(parents)
totals = list(spend)
for v in range(1, n):
totals[parents[v]] += totals[v]
return totalsThe Academy lessons Trees and BSTs and Tree recursion taught the walk, and Lowest common ancestor answered one pair at a time. Graph traversal gave you the queue that builds the order. This tent keeps those ideas and changes the scale: answers for all nodes, trips by the thousand, and the best of all roots.
Two new tools come with the scale. The first is the distance from the root. A trip between towns a and b is the distance of a, plus the distance of b, minus twice the distance of their lowest common ancestor. Each distance is one forward sweep.
The second is rerooting. Put the depot at node 0 and price it with two sweeps. Moving the depot across one road to node v brings the demand of v's subtree one road closer and pushes all other demand one road farther. The cost changes by the road length times (whole demand - 2 × the demand below v), so every other root costs one step more.
The diameter hides a trap. It is tempting to take the two deepest branches of the root. The longest path may avoid the root altogether.
The longest path of a tree can avoid the root, so take the two deepest branches at every node.
Exercise · Break it: The longest path that skips the root. Every node's parent has a smaller number, and parents[0] is -1. This returns the number of links on the longest path. It adds the two deepest branches of the root. Find an input where it is wrong.
def longest_path(parents):
n = len(parents)
height = [0] * n
for v in range(n - 1, 0, -1):
height[parents[v]] = max(height[parents[v]], height[v] + 1)
first = 0
second = 0
for v in range(1, n):
if parents[v] == 0:
reach = height[v] + 1
if reach > first:
second = first
first = reach
elif reach > second:
second = reach
return first + second| Limit | What it tells you |
|---|---|
| 10^5 nodes | a chain is possible: no recursion, or raise the stack |
| spend up to 10^9 on 10^5 nodes | totals reach 10^14: 64-bit integers |
| 5 × 10^4 trips | each one must cost a constant or a logarithm |
| demand up to 100, roads up to 1,000 | a cost reaches about 10^5 × 100 × 10^8 = 10^15: 64-bit |
| every root wanted | the answer is a table, not one number |
The full treatment is in Fast I/O and stress testing. Contest trees often list the parent of nodes 2 to n, with each parent numbered below its child. Then the node numbers are already the order, and the backward sweep is a plain loop.
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]]
size = [1] * (n + 1)
for v in range(n, 1, -1):
size[parent[v]] += size[v]
sys.stdout.write(" ".join(map(str, size[1:])) + "\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[] parent = new int[n + 1];
for (int v = 2; v <= n; v++) {
in.nextToken();
parent[v] = (int) in.nval;
}
int[] size = new int[n + 1];
Arrays.fill(size, 1);
for (int v = n; v >= 2; v--) size[parent[v]] += size[v];
StringBuilder out = new StringBuilder();
for (int v = 1; v <= n; v++) out.append(size[v]).append(v < n ? " " : "\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;
vector<int> parent(n + 1, 0), size(n + 1, 1);
for (int v = 2; v <= n; v++) cin >> parent[v];
for (int v = n; v >= 2; v--) size[parent[v]] += size[v];
for (int v = 1; v <= n; v++) cout << size[v] << (v < n ? " " : "\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 size = new Array(n + 1).fill(1);
for (let v = n; v >= 2; v--) size[parent[v]] += size[v];
process.stdout.write(size.slice(1).join(" ") + "\n");On the sample 6 and 1 1 2 2 3, which means that nodes 2 to 6 hang from nodes 1, 1, 2, 2 and 3, all four programs print 6 3 2 1 1 1.
The slow twin is the recursive walk: for every node, count its subtree by recursion. It is only safe on small trees, which is all a stress test needs.
import random
from fast import subtree_sizes
from slow import subtree_sizes as slow_sizes
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 8)
parents = [-1] + [rng.randint(0, i - 1) for i in range(1, n)]
if subtree_sizes(parents) != slow_sizes(parents):
print("different at", parents)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Make the sweep run forwards and seed 0 fails: the parents -1, 0, 0, 1, 3, 3, 2 give 3 for the root instead of 7.
At 1,600 to 1,800 the idea is known and the work is choosing the sweep. Write which direction each value flows before you code. Aim for about 30 minutes a problem, and keep 10 for a stress test on trees of up to 8 nodes.
The first two are backward sweeps. The diameter needs forward sweeps from two starts. The trips add the distance from the root and the lowest common ancestor. The depot, rated 1,800, uses both directions and moves the root.
For each problem, write in one line which value flows up and which flows down. Then write the recursive twin for trees of up to 8 nodes, and stress test.
Checkpoint · Trees for contests
Q1/5 A tree has 10^5 nodes and you need the total of every subtree. Why is a recursive walk from each node a poor plan?
Answer: B
A chain of 10^5 nodes costs 1 + 2 + ... + 10^5 = 5,000,050,000 steps for the walks. One order and one backward sweep cost 10^5.
Q2/5 In which direction do you sweep the order to add every node's total to its parent?
Answer: B
Backwards, a node is reached only after all its children, so its total is complete. Forwards, with the parents -1, 0, 1 and the spend 1, 1, 1, the root gets 2 instead of 3.
Q3/5 A tree has the parents -1, 0, 1, 1, 2, 3. What is the number of links on its longest path?
Answer: B
The path 4, 2, 1, 3, 5 has 4 links. The two deepest branches of the root give only 3, because the root has a single child.
Q4/5 After pricing a depot at node 0, how do you price the depot at a child v?
Answer: B
Moving across the road brings the demand below v one road closer and pushes the rest one road farther. That is a change of road length × (whole - 2 × below).
Q5/5 What does a rating of 1,600 to 1,800 usually ask of you?
Answer: B
The ideas here are sweeps, distances and rerooting. The work is choosing what flows up, what flows down and which integers must be 64-bit.
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.