Six problems rated 1,800 to 2,000 that ask about ranges while values change. The move: decide what a node stores so two children merge into their parent, then every update and query walks about 17 levels.
This tent holds six problems rated 1,800 to 2,000. Each one asks about a range of up to 10^5 values: a sum, a count of ties, a first position, a count of different values. In most of them the values change between questions.
Prefix sums answer a range in two reads, but one change forces a rebuild. A scan answers anything and costs the length of the range. Both fail at the limits.
| Problem | The literal route | Its size at the limits |
|---|---|---|
| Waiting minutes at a pickup zone | add up the range for each question | 2.5 × 10^9 steps |
| Replicas tied for the fastest response | scan the range for each question | 10^10 steps |
| Posts that slide three places | try every triple of posts | 166,661,666,700,000 triples |
| Ramped budget boosts | change every hour of each boost | 4 × 10^8 steps |
| First truck with room | scan from the start for each request | 10^10 steps |
| Different documents in a stretch | build a set for each range | 10^10 steps |
A segment tree does an update and a query in about 17 steps, because log2 of 10^5 is 16.6.
Exercise · Predict the output: A point update and a range query. A sum tree over 4 values keeps the leaves at positions 4 to 7, and node i has the children 2i and 2i + 1. This sets the value at position 2 to 1, then adds up the positions 1 to 3. What does it print: the sum, then the total at the root?
n = 4
tree = [0] * 8
for i, v in enumerate([5, 3, 8, 6]):
tree[n + i] = v
for i in range(n - 1, 0, -1):
tree[i] = tree[2 * i] + tree[2 * i + 1]
i = n + 2
tree[i] = 1
while i > 1:
i //= 2
tree[i] = tree[2 * i] + tree[2 * i + 1]
lo, hi = 1 + n, 4 + n
total = 0
while lo < hi:
if lo % 2 == 1:
total += tree[lo]
lo += 1
if hi % 2 == 1:
hi -= 1
total += tree[hi]
lo //= 2
hi //= 2
print(total, tree[1])A segment tree is a binary tree over the positions. Each node covers a range and stores a summary of it. The leaves are single values, and a node is the merge of its two children.
Decide what a node stores so that two halves merge into their parent in constant time. Then an update fixes one path of about 17 nodes, and a query merges at most two nodes on each level.
What a node stores is the whole problem. For a sum it is one number. For the replicas it is the lowest value and the count of ties, and for the trucks it is the maximum. The waiting-minutes problem weights each value by its position, so a node keeps the sum and the sum of value × position.
Two further variants appear in the ladder. A range update uses lazy propagation: it stores a lazy tag on a node and applies it to the children only when a later question needs them. A search for the first position with enough room walks down from the root, going left whenever the left child has a large enough maximum.
A node stores the lowest value and its count; merging two blocks adds the counts when the lowest values are equal.
Exercise · Find the bug: The tie that is counted once. This merges two blocks into the count of replicas that share the lowest response time. Each block gives its lowest time and how many replicas have it. Which line is wrong?
def merge_ties(a_min, a_count, b_min, b_count):
if a_min < b_min:
return a_count
if b_min < a_min:
return b_count
return a_countThe Academy lessons Prefix sums, Merge sort and inversions and Divide and conquer gave you range totals, counted pairs and halving. First-true template showed a search on a yes or no answer. This tent combines them. Halving builds the tree, and a search walks down it.
A Fenwick tree is the compact form for totals that start at position 0. It counts the inversions in n log n steps: for each value, ask how many earlier values were larger. The triples of the ladder multiply two such counts for every middle value.
When all questions are known in advance, there is a second tool. Sort the questions by right end and move across the values from left to right. Keep a mark only at the latest place of each value, so the number of different values in a range is the number of marks inside it.
Count the triples with care. The two comparisons must be strict, or equal scores count as both larger and smaller.
A slide needs strictly falling scores; comparing with greater or equal makes equal scores count as both higher and lower.
Exercise · Break it: The scores that tie. A slide is three posts i < j < k with scores[i] > scores[j] > scores[k]. For each middle post this multiplies the count of earlier posts that are not lower by the count of later posts that are not higher. Find an input where it is wrong.
def count_slides(scores):
n = len(scores)
total = 0
for j in range(n):
left = 0
for i in range(j):
if scores[i] >= scores[j]:
left += 1
right = 0
for k in range(j + 1, n):
if scores[k] <= scores[j]:
right += 1
total += left * right
return total| Limit | What it tells you |
|---|---|
| 10^5 values, 10^5 operations | a tree of 2 × 10^5 nodes and about 17 steps per operation |
| 10^5 operations on 10^5 values | about 3.4 × 10^6 steps in all, which is safe in every language |
| counts of triples up to 1.7 × 10^14 | 64-bit integers for every total |
| a range update on 2 × 10^4 hours | lazy propagation, not a loop over the hours |
| all questions known in advance | sort them by right end and use a Fenwick tree |
The full treatment is in Fast I/O and stress testing. The tree below is the bottom-up form from the exercise. It stores the leaves at positions n to 2n - 1, and the answers are printed together at the end.
import sys
def main():
data = sys.stdin.buffer.read().split()
n, q = int(data[0]), int(data[1])
tree = [0] * (2 * n)
for i in range(n):
tree[n + i] = int(data[2 + i])
for i in range(n - 1, 0, -1):
tree[i] = tree[2 * i] + tree[2 * i + 1]
out = []
at = 2 + n
for _ in range(q):
kind, a, b = int(data[at]), int(data[at + 1]), int(data[at + 2])
at += 3
if kind == 0:
i = n + a
tree[i] = b
while i > 1:
i //= 2
tree[i] = tree[2 * i] + tree[2 * i + 1]
else:
lo, hi, total = a + n, b + 1 + n, 0
while lo < hi:
if lo % 2 == 1:
total += tree[lo]
lo += 1
if hi % 2 == 1:
hi -= 1
total += tree[hi]
lo //= 2
hi //= 2
out.append(total)
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;
in.nextToken();
int q = (int) in.nval;
long[] tree = new long[2 * n];
for (int i = 0; i < n; i++) {
in.nextToken();
tree[n + i] = (long) in.nval;
}
for (int i = n - 1; i >= 1; i--) tree[i] = tree[2 * i] + tree[2 * i + 1];
StringBuilder out = new StringBuilder();
for (int t = 0; t < q; t++) {
in.nextToken();
int kind = (int) in.nval;
in.nextToken();
int a = (int) in.nval;
in.nextToken();
int b = (int) in.nval;
if (kind == 0) {
int i = n + a;
tree[i] = b;
while (i > 1) {
i /= 2;
tree[i] = tree[2 * i] + tree[2 * i + 1];
}
} else {
int lo = a + n, hi = b + 1 + n;
long total = 0;
while (lo < hi) {
if (lo % 2 == 1) total += tree[lo++];
if (hi % 2 == 1) total += tree[--hi];
lo /= 2;
hi /= 2;
}
out.append(total).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, q;
cin >> n >> q;
vector<long long> tree(2 * n, 0);
for (int i = 0; i < n; i++) cin >> tree[n + i];
for (int i = n - 1; i >= 1; i--) tree[i] = tree[2 * i] + tree[2 * i + 1];
for (int t = 0; t < q; t++) {
int kind, a, b;
cin >> kind >> a >> b;
if (kind == 0) {
int i = n + a;
tree[i] = b;
while (i > 1) {
i /= 2;
tree[i] = tree[2 * i] + tree[2 * i + 1];
}
} else {
int lo = a + n, hi = b + 1 + n;
long long total = 0;
while (lo < hi) {
if (lo % 2 == 1) total += tree[lo++];
if (hi % 2 == 1) total += tree[--hi];
lo /= 2;
hi /= 2;
}
cout << total << "\n";
}
}
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0], q = data[1];
const tree = new Array(2 * n).fill(0);
for (let i = 0; i < n; i++) tree[n + i] = data[2 + i];
for (let i = n - 1; i >= 1; i--) tree[i] = tree[2 * i] + tree[2 * i + 1];
const out = [];
let at = 2 + n;
for (let t = 0; t < q; t++) {
const kind = data[at], a = data[at + 1], b = data[at + 2];
at += 3;
if (kind === 0) {
let i = n + a;
tree[i] = b;
while (i > 1) {
i = Math.floor(i / 2);
tree[i] = tree[2 * i] + tree[2 * i + 1];
}
} else {
let lo = a + n, hi = b + 1 + n, total = 0;
while (lo < hi) {
if (lo % 2 === 1) total += tree[lo++];
if (hi % 2 === 1) total += tree[--hi];
lo = Math.floor(lo / 2);
hi = Math.floor(hi / 2);
}
out.push(total);
}
}
process.stdout.write(out.join("\n") + "\n");On the sample with 5 values 5 3 8 6 2 and the four operations 1 1 3, 0 2 1, 1 1 3 and 1 0 4, all four programs print 17, 10 and 17, one per line.
The slow twin keeps a plain list and adds up the range with a loop. It cannot share a tree mistake with the fast code.
import random
from fast import SegmentTree
def agrees(seed):
rng = random.Random(seed)
n = rng.randint(1, 8)
values = [rng.randint(0, 9) for _ in range(n)]
tree = SegmentTree(values)
for _ in range(10):
if rng.random() < 0.4:
i, v = rng.randrange(n), rng.randint(0, 9)
values[i] = v
tree.set(i, v)
else:
a = rng.randrange(n)
b = rng.randrange(a, n)
if tree.query(a, b) != sum(values[a:b + 1]):
return False
return True
for seed in range(1000):
if not agrees(seed):
print("different at seed", seed)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Read the range as half-open, with the end at b instead of b + 1, and seed 0 fails. For the values 6, 0, 4, 8, 7, 6, 4 and the range 2 to 6 it gives 25 instead of 29.
At 1,800 to 2,000 the structure is known, and the work is the node: what it stores and how two halves merge. Write the stored fields and the merge in two lines before you code. Aim for about 40 minutes a problem, and keep 10 for the stress test.
The three problems rated 1,800 are the plain forms: a weighted sum, a minimum with ties, and a Fenwick count. The two rated 1,900 add a lazy tag and a descent. The last, rated 2,000, answers questions offline.
For each problem, write what a node stores and how two children merge, in two lines. Then write the slow twin with a plain list, and stress test on 8 values.
Checkpoint · Segment trees for contests
Q1/5 Values change between range questions, with 10^5 of each. Why are prefix sums not enough?
Answer: B
Prefix sums are perfect when nothing changes. A segment tree fixes one path of about 17 nodes for each change.
Q2/5 Which pair does a node store to count how many replicas tie for the lowest response time?
Answer: B
Two children with the same lowest value add their counts. Storing only a position loses every other tie.
Q3/5 Two blocks both have the lowest time 2, with 1 and 3 replicas. What count does the merged node get?
Answer: C
Equal lowest times mean the replicas of both blocks tie, so the counts add: 1 + 3 = 4.
Q4/5 For the scores 5, 5, 5 how many slides, with scores[i] > scores[j] > scores[k], are there?
Answer: B
No score is strictly higher than another. A non-strict comparison would count 1, because equal scores count as both larger and smaller.
Q5/5 All the questions are known in advance, and each asks for the number of different values in a range. What is the plan?
Answer: B
Moving the right end from left to right, the marks inside a range are exactly its different values. A Fenwick tree counts them in two reads.
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.