Three problems rated 1,900 to 2,000 that a segment tree does not fit. The move: cut the work into blocks of about the square root of n, or answer the questions in an order that makes each one cheap.
This tent holds three problems rated 1,900 to 2,000. Each one is a question that a plain segment tree cannot hold. One counts values above a threshold after range additions. One counts the values that repeat in a range, and one finds the nearest of points that keep appearing.
The first solution handles every operation by scanning. It is correct, and it is slow.
| Problem | The literal route | Its size at the limits |
|---|---|---|
| Accounts above a balance after bonuses | scan the range for each operation | 4 × 10^8 steps |
| Flaky tests in a range of builds | count the values of each range | 10^10 steps |
| Distance to the nearest charging station | scan every station for each question | 9 × 10^8 steps |
Blocks of about the square root of n cut each of these to about sqrt(n) steps per operation.
Exercise · Predict the output: Two bonuses on blocks of three. Ten accounts start at 0 and are cut into blocks of 3. A bonus on a range gives a whole block one pending value and changes the other accounts directly. This adds 5 to accounts 2 to 7, then 3 to accounts 4 to 9. What does it print: the balances of accounts 2, 4, 8 and 9?
B = 3
lazy = [0] * 4
a = [0] * 10
def add(l, r, x):
i = l
while i <= r:
if i % B == 0 and i + B - 1 <= r:
lazy[i // B] += x
i += B
else:
a[i] += x
i += 1
add(2, 7, 5)
add(4, 9, 3)
print(*[a[i] + lazy[i // B] for i in (2, 4, 8, 9)])Cut the n positions into blocks of about sqrt(n) positions. For 20,000 accounts a block holds 141 accounts, and there are 142 blocks.
Handle whole blocks through a stored summary and a pending tag, and the two partial ends one element at a time. Each operation then costs about sqrt(n) steps.
A range touches at most two partial blocks and many whole blocks. For the whole blocks, a bonus is one pending value, and a count is one binary search in the block's sorted copy. For the partial blocks, change or read the elements directly, and rebuild the sorted copy of that block.
The cost for 20,000 operations is 20,000 × (142 blocks × 8 search steps + 2 × 141 partial elements) = 28,360,000 steps. The scan costs 4 × 10^8.
The offline problem uses a different cut. Its questions are known in advance, so sort them by right end and sweep the values once from left to right. Keep a mark only at the second latest place of each value. A question is then a count of marks inside its range.
A whole block gets one pending value and a partial block is changed directly: a range bonus costs about the square root of n.
Exercise · Find the bug: The balance that equals the threshold. A block keeps its balances in sorted order, and a pending value that was added to all of them. This counts the accounts in the block whose balance is at least x. Which line is wrong?
def count_at_least(block, pending, x):
need = x - pending
lo, hi = 0, len(block)
while lo < hi:
mid = (lo + hi) // 2
if block[mid] <= need:
lo = mid + 1
else:
hi = mid
return len(block) - loThe Academy lessons Difference arrays and Lower and upper bound gave you range additions and the two search bounds. Comparators covered sorting by your own key, and Common classes felt showed what sqrt(n) steps cost. This tent puts them together under one rule: the work per operation is about sqrt(n).
Why not a segment tree? A node would have to hold every balance, to count the ones above any threshold, and a range update would make that summary expensive to fix. A block can keep a whole sorted copy, because only about sqrt(n) of them are touched.
The offline sweep has its own trap. When a value appears a third time, its second latest place moves. The old mark must go.
When a value appears again, its second latest place moves, so the old mark must be cleared or the value counts twice.
Exercise · Break it: The mark that is never removed. failures[i] is the test that failed in build i. Each question asks how many different tests failed at least twice in builds l to r. The questions are sorted by right end. Each value keeps a mark at its second latest place. Find an input where it is wrong.
def repeat_offenders(failures, queries):
n = len(failures)
order = sorted(range(len(queries)), key=lambda q: queries[q][1])
marks = [0] * n
latest = {}
second = {}
answers = [0] * len(queries)
at = 0
for q in order:
l, r = queries[q]
while at <= r:
test = failures[at]
if test in latest:
marks[latest[test]] = 1
second[test] = latest[test]
latest[test] = at
at += 1
answers[q] = sum(marks[l:r + 1])
return answers| Limit | What it tells you |
|---|---|
| 20,000 accounts, 20,000 operations | blocks of 141: about 2.8 × 10^7 steps in all |
| 30,000 marks, 30,000 operations | rebuild every 173 openings: about 10^7 steps |
| 10^5 questions known in advance | sort by right end and sweep once |
| balances up to 10^6 plus 20,000 bonuses of 10^8 | totals reach 2 × 10^12: 64-bit integers |
| block size | about sqrt(n), and at least 1, so the code works for n = 1 |
The full treatment is in Fast I/O and stress testing. The input holds the counts of accounts and operations, then the balances, then one row per operation. A row has four numbers: a kind (0 adds, 1 counts), the two ends, and x. The blocks keep their own sorted copies.
import sys
from bisect import bisect_left
def main():
data = sys.stdin.buffer.read().split()
n, q = int(data[0]), int(data[1])
a = [int(x) for x in data[2:2 + n]]
B = max(1, int(n ** 0.5))
blocks = (n + B - 1) // B
lazy = [0] * blocks
srt = [sorted(a[b * B:(b + 1) * B]) for b in range(blocks)]
out = []
at = 2 + n
for _ in range(q):
kind, l, r, x = (int(v) for v in data[at:at + 4])
at += 4
bl, br = l // B, r // B
if kind == 0:
for i in range(l, r + 1 if bl == br else (bl + 1) * B):
a[i] += x
srt[bl] = sorted(a[bl * B:(bl + 1) * B])
if bl != br:
for i in range(br * B, r + 1):
a[i] += x
srt[br] = sorted(a[br * B:(br + 1) * B])
for b in range(bl + 1, br):
lazy[b] += x
else:
total = 0
if bl == br:
for i in range(l, r + 1):
total += a[i] + lazy[bl] >= x
else:
for i in range(l, (bl + 1) * B):
total += a[i] + lazy[bl] >= x
for i in range(br * B, r + 1):
total += a[i] + lazy[br] >= x
for b in range(bl + 1, br):
total += len(srt[b]) - bisect_left(srt[b], x - lazy[b])
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[] a = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
int B = Math.max(1, (int) Math.sqrt(n));
int blocks = (n + B - 1) / B;
long[] lazy = new long[blocks];
long[][] srt = new long[blocks][];
for (int b = 0; b < blocks; b++) srt[b] = sortedBlock(a, b, B, n);
StringBuilder out = new StringBuilder();
for (int t = 0; t < q; t++) {
in.nextToken();
int kind = (int) in.nval;
in.nextToken();
int l = (int) in.nval;
in.nextToken();
int r = (int) in.nval;
in.nextToken();
long x = (long) in.nval;
int bl = l / B, br = r / B;
if (kind == 0) {
int end = bl == br ? r + 1 : (bl + 1) * B;
for (int i = l; i < end; i++) a[i] += x;
srt[bl] = sortedBlock(a, bl, B, n);
if (bl != br) {
for (int i = br * B; i <= r; i++) a[i] += x;
srt[br] = sortedBlock(a, br, B, n);
for (int b = bl + 1; b < br; b++) lazy[b] += x;
}
} else {
int total = 0;
if (bl == br) {
for (int i = l; i <= r; i++) if (a[i] + lazy[bl] >= x) total++;
} else {
for (int i = l; i < (bl + 1) * B; i++) if (a[i] + lazy[bl] >= x) total++;
for (int i = br * B; i <= r; i++) if (a[i] + lazy[br] >= x) total++;
for (int b = bl + 1; b < br; b++) {
long need = x - lazy[b];
int lo = 0, hi = srt[b].length;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (srt[b][mid] < need) lo = mid + 1;
else hi = mid;
}
total += srt[b].length - lo;
}
}
out.append(total).append("\n");
}
}
System.out.print(out);
}
static long[] sortedBlock(long[] a, int b, int B, int n) {
long[] copy = Arrays.copyOfRange(a, b * B, Math.min(n, (b + 1) * B));
Arrays.sort(copy);
return copy;
}
}#include <algorithm>
#include <cmath>
#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> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
int B = max(1, (int) sqrt((double) n));
int blocks = (n + B - 1) / B;
vector<long long> lazy(blocks, 0);
vector<vector<long long>> srt(blocks);
auto rebuild = [&](int b) {
srt[b].assign(a.begin() + b * B, a.begin() + min(n, (b + 1) * B));
sort(srt[b].begin(), srt[b].end());
};
for (int b = 0; b < blocks; b++) rebuild(b);
for (int t = 0; t < q; t++) {
int kind, l, r;
long long x;
cin >> kind >> l >> r >> x;
int bl = l / B, br = r / B;
if (kind == 0) {
int end = bl == br ? r + 1 : (bl + 1) * B;
for (int i = l; i < end; i++) a[i] += x;
rebuild(bl);
if (bl != br) {
for (int i = br * B; i <= r; i++) a[i] += x;
rebuild(br);
for (int b = bl + 1; b < br; b++) lazy[b] += x;
}
} else {
int total = 0;
if (bl == br) {
for (int i = l; i <= r; i++) total += a[i] + lazy[bl] >= x;
} else {
for (int i = l; i < (bl + 1) * B; i++) total += a[i] + lazy[bl] >= x;
for (int i = br * B; i <= r; i++) total += a[i] + lazy[br] >= x;
for (int b = bl + 1; b < br; b++) {
total += srt[b].end() - lower_bound(srt[b].begin(), srt[b].end(), x - lazy[b]);
}
}
cout << total << "\n";
}
}
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0], q = data[1];
const a = data.slice(2, 2 + n);
const B = Math.max(1, Math.floor(Math.sqrt(n)));
const blocks = Math.floor((n + B - 1) / B);
const lazy = new Array(blocks).fill(0);
const sortedBlock = (b) => a.slice(b * B, Math.min(n, (b + 1) * B)).sort((u, v) => u - v);
const srt = [];
for (let b = 0; b < blocks; b++) srt.push(sortedBlock(b));
const out = [];
let at = 2 + n;
for (let t = 0; t < q; t++) {
const kind = data[at], l = data[at + 1], r = data[at + 2], x = data[at + 3];
at += 4;
const bl = Math.floor(l / B), br = Math.floor(r / B);
if (kind === 0) {
const end = bl === br ? r + 1 : (bl + 1) * B;
for (let i = l; i < end; i++) a[i] += x;
srt[bl] = sortedBlock(bl);
if (bl !== br) {
for (let i = br * B; i <= r; i++) a[i] += x;
srt[br] = sortedBlock(br);
for (let b = bl + 1; b < br; b++) lazy[b] += x;
}
} else {
let total = 0;
if (bl === br) {
for (let i = l; i <= r; i++) if (a[i] + lazy[bl] >= x) total++;
} else {
for (let i = l; i < (bl + 1) * B; i++) if (a[i] + lazy[bl] >= x) total++;
for (let i = br * B; i <= r; i++) if (a[i] + lazy[br] >= x) total++;
for (let b = bl + 1; b < br; b++) {
const need = x - lazy[b];
let lo = 0, hi = srt[b].length;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (srt[b][mid] < need) lo = mid + 1;
else hi = mid;
}
total += srt[b].length - lo;
}
}
out.push(total);
}
}
process.stdout.write(out.join("\n") + "\n");On the sample with 6 accounts 1 5 3 7 2 6 and the four operations 1 0 5 4, 0 1 4 2, 1 0 5 4 and 1 2 3 6, all four programs print 3, 5 and 1, one per line.
The slow twin keeps a plain list, adds to a range with a loop, and counts a range with a loop. It cannot share a block mistake with the fast code.
import random
from fast import count_at_least
from slow import count_at_least as slow_count
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 12)
balances = [rng.randint(0, 9) for _ in range(n)]
ops = []
for _ in range(10):
l = rng.randrange(n)
ops.append([rng.randint(0, 1), l, rng.randrange(l, n), rng.randint(0, 9)])
if count_at_least(balances, ops) != slow_count(balances, ops):
print("different at seed", seed)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Count with an upper bound instead of a lower bound, and seed 7 fails, with a list of 6 balances.
At 1,800 to 2,000 the cut is the idea, and the care is in the partial blocks. Write the block size and the cost of one operation in a line before you code. Aim for about 40 minutes a problem, and keep 10 for the stress test on up to 12 values.
The first problem is the plain blocks, with a pending value and a sorted copy. The two rated 2,000 change the cut: one sorts the questions by right end, and one rebuilds a table after about sqrt(q) changes.
For each problem, write the block size and the cost of one operation in a line. Then write the slow twin with plain loops, and stress test on up to 12 values.
Checkpoint · Square-root and offline tricks
Q1/5 For 20,000 accounts, what is the block size, and how many blocks are there?
Answer: B
The square root of 20,000 is about 141.4, so a block holds 141 accounts and 142 blocks cover them.
Q2/5 How does a bonus on a range treat a whole block, and how does it treat a partial block?
Answer: B
The pending value costs one step for a whole block. A partial block holds at most 141 accounts, so changing them one by one is cheap.
Q3/5 A block holds the sorted balances 1, 3, 3, 7 with no pending value. How many are at least 3?
Answer: C
The balances 3, 3 and 7 count. An upper bound would skip the two 3s and find 1.
Q4/5 Why do you sort offline questions by right end?
Answer: B
When the right end moves right, a value's marks change only at its newest places. Each question is a count of marks inside its range.
Q5/5 The tests fail in the builds 1, 1, 1. How many tests failed at least twice in builds 0 to 2?
Answer: B
One test, counted once. If the old mark is not cleared when the third failure arrives, the sweep counts 2.
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.