Three problems rated 2,300 to 2,400 where all questions are known in advance. The move: answer them in an order that makes the work between two answers small, or split them by time.
Each problem in this tent hands you all its questions at once. You never have to answer them in the order they arrive, and that freedom is the whole idea.
The table shows what answering each question from scratch costs, and what the offline idea changes.
| Problem | From scratch | At the limits | The offline idea |
|---|---|---|---|
| Different terms in ranges of a search log | count each range on its own | 20,000 ranges: 133,704,588 element visits on a random log | slide one window from range to range |
| Audit questions on a stream of transactions | scan the earlier transactions for each question | 40,000 events: 800,000,000 pairs | split by time and count across the halves |
| Different services on a dashboard while labels change | rebuild the window after each edit | 15,000 operations | add time as a third coordinate |
The cost of the offline idea is the movement between answers. If two neighbouring questions are close, the work between them is small.
Here is the sorting rule of Mo's algorithm on seven questions about a log of 9 positions. The block is 3. The code sorts the questions by the block of the left end, and then by the right end: up in even blocks and down in odd blocks.
Exercise · Predict the output: The order of the questions. The questions are the ranges (0,8), (7,8), (1,2), (3,4), (6,7), (2,7) and (4,8), numbered from 0. The block is 3. What order of question numbers does the code print?
ranges = [(0, 8), (7, 8), (1, 2), (3, 4), (6, 7), (2, 7), (4, 8)]
block = 3
order = sorted(range(len(ranges)), key=lambda i: (ranges[i][0] // block, ranges[i][1] if (ranges[i][0] // block) % 2 == 0 else -ranges[i][1]))
print(" ".join(map(str, order)))The move has two forms, and both answer the questions in an order you choose.
For range questions, keep one window with two pointers, and a table of counts. Move the pointers from one question to the next. The total work is the total distance the pointers travel, so the order of the questions decides the cost.
Mo's order makes that distance small. Cut the positions into blocks of about n divided by the square root of q. Sort by the block of the left end, then by the right end, going down in odd blocks. The left pointer moves less than a block between questions, and the right pointer sweeps once for each block.
The window always holds the answer of the current question. The total work is the distance the pointers travel, so sort the questions to keep that distance small.
For 20,000 random ranges on a log of 20,000 terms, the block is 141. The pointers move 212,810,043 steps in the given order, and 2,381,624 steps in Mo's order.
The window starts empty, with left at 0 and right at -1. The first question then adds its elements one by one, and no special case is needed.
Sort by the block of the left end, then by the right end, up and down. Seven questions go 2, 5, 0, 6, 3, 4, 1.
The start of the window is easy to write one step wrong.
Exercise · Find the bug: The window that starts full. This answers each range with a window that moves from one range to the next, and a table of counts. It fails on the smallest input. Which line is wrong?
def distinct_in_ranges(terms, ranges):
seen = [0] * (max(terms) + 1)
distinct, left, right = 0, 0, 0
answers = []
for l, r in ranges:
while left > l:
left -= 1
seen[terms[left]] += 1
if seen[terms[left]] == 1: distinct += 1
while right < r:
right += 1
seen[terms[right]] += 1
if seen[terms[right]] == 1: distinct += 1
while left < l:
seen[terms[left]] -= 1
if seen[terms[left]] == 0: distinct -= 1
left += 1
while right > r:
seen[terms[right]] -= 1
if seen[terms[right]] == 0: distinct -= 1
right -= 1
answers.append(distinct)
return answersThe Academy lessons Range queries, Comparators and Merge sort and inversions taught prefix tables, custom sort orders and counting across two halves. Common classes felt gave you a feel for 10^8 steps. This tent changes three things.
The order is the algorithm. There is no data structure to build, only an order of questions to choose. The block size is a parameter you must tune, about n divided by the square root of q.
Edits add a coordinate. When labels change between questions, a question needs the state at its own moment. Add time as a third coordinate, and use blocks of about n to the power of two thirds. On 15,000 operations with about 7,500 questions, the pointers move 59,339,574 steps in the given order and 7,715,609 steps in the sorted order.
A split by time counts pairs. For questions about earlier items under two limits, split the events at the middle. Solve both halves, then count the pairs across them with both halves sorted by amount and a Fenwick tree over the fees. For 40,000 events that is about 9,348,566 steps, and not 800,000,000.
A presence flag clears when one of two equal terms leaves. A count drops to zero only when the last copy leaves.
A window needs counts. A presence flag looks like enough, and it is not.
Exercise · Break it: A flag instead of a count. This answers each range with a moving window, and it keeps a flag for each term that says whether the term is in the window. Find an input where it gives a wrong count.
def distinct_in_ranges(terms, ranges):
present = [False] * (max(terms) + 1)
distinct, left, right = 0, 0, -1
answers = []
for l, r in ranges:
while left > l:
left -= 1
if not present[terms[left]]:
present[terms[left]] = True
distinct += 1
while right < r:
right += 1
if not present[terms[right]]:
present[terms[right]] = True
distinct += 1
while left < l:
if present[terms[left]]:
present[terms[left]] = False
distinct -= 1
left += 1
while right > r:
if present[terms[right]]:
present[terms[right]] = False
distinct -= 1
right -= 1
answers.append(distinct)
return answersThe limits tell you which offline idea to use, and the block size.
| Limit | What it tells you |
|---|---|
| 20,000 positions, 20,000 ranges | Mo's order, block 141: about 2.4 × 10^6 pointer steps |
| 15,000 operations with edits | blocks of about n^(2/3), here 609: about n^(5/3) |
| 40,000 events, two limits | divide and conquer on time, about n log² n |
| counts of pairs | up to 800,000,000 here: use 64 bits when n can grow |
| block size | at least 1, so that n = 1 works |
The full treatment is in Fast I/O and stress testing. The first line holds n and q, the second the values, and then one line per range. Sorting has to be fast too, so the program sorts the question numbers, not the ranges. It prints the order of the questions.
It was run on the sample of 9 values and the 7 ranges of the prediction above. All four programs print 2 5 0 6 3 4 1.
import sys
def main():
data = sys.stdin.buffer.read().split()
n, q = int(data[0]), int(data[1])
at = 2 + n
ls = [int(data[at + 2 * i]) for i in range(q)]
rs = [int(data[at + 2 * i + 1]) for i in range(q)]
block = max(1, int(n / q ** 0.5))
order = sorted(range(q), key=lambda i: (ls[i] // block, rs[i] if (ls[i] // block) % 2 == 0 else -rs[i]))
sys.stdout.write(" ".join(map(str, order)) + "\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;
for (int i = 0; i < n; i++) in.nextToken();
int[] ls = new int[q], rs = new int[q];
for (int i = 0; i < q; i++) {
in.nextToken();
ls[i] = (int) in.nval;
in.nextToken();
rs[i] = (int) in.nval;
}
int block = Math.max(1, (int) (n / Math.sqrt(q)));
Integer[] order = new Integer[q];
for (int i = 0; i < q; i++) order[i] = i;
Arrays.sort(order, (x, y) -> {
int bx = ls[x] / block, by = ls[y] / block;
if (bx != by) return bx - by;
return bx % 2 == 0 ? rs[x] - rs[y] : rs[y] - rs[x];
});
StringBuilder out = new StringBuilder();
for (int i = 0; i < q; i++) out.append(order[i]).append(i + 1 < q ? " " : "\n");
System.out.print(out);
}
}#include <algorithm>
#include <cmath>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, q;
cin >> n >> q;
vector<int> a(n), ls(q), rs(q);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < q; i++) cin >> ls[i] >> rs[i];
int block = max(1, (int)(n / sqrt((double)q)));
vector<int> order(q);
iota(order.begin(), order.end(), 0);
sort(order.begin(), order.end(), [&](int x, int y) {
int bx = ls[x] / block, by = ls[y] / block;
if (bx != by) return bx < by;
return bx % 2 == 0 ? rs[x] < rs[y] : rs[x] > rs[y];
});
for (int i = 0; i < q; i++) cout << order[i] << (i + 1 < q ? " " : "\n");
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0], q = data[1];
const at = 2 + n;
const ls = [], rs = [];
for (let i = 0; i < q; i++) {
ls.push(data[at + 2 * i]);
rs.push(data[at + 2 * i + 1]);
}
const block = Math.max(1, Math.floor(n / Math.sqrt(q)));
const order = Array.from({ length: q }, (_, i) => i);
order.sort((x, y) => {
const bx = Math.floor(ls[x] / block), by = Math.floor(ls[y] / block);
if (bx !== by) return bx - by;
return bx % 2 === 0 ? rs[x] - rs[y] : rs[y] - rs[x];
});
process.stdout.write(order.join(" ") + "\n");A wrong window start or a flag instead of a count gives answers that look plausible. Compare the fast code with the brute force on small random logs, and stop at the first difference.
import random
from fast import distinct_in_ranges
from slow import distinct_in_ranges as slow_distinct
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 12)
terms = [rng.randint(0, 4) for _ in range(n)]
ranges = []
for _ in range(rng.randint(1, 8)):
a, b = rng.randrange(n), rng.randrange(n)
ranges.append([min(a, b), max(a, b)])
if distinct_in_ranges(terms, ranges) != slow_distinct(terms, ranges):
print("different at seed", seed, terms, ranges)
break
else:
print("all 1000 inputs agree")On the Mo solution it printed all 1000 inputs agree. With the right pointer starting at 0, it stops at seed 0.
Problems rated 2,200 to 2,400 need the offline idea and the care to write it without a slip. Choose the block size from the limits. Keep 15 minutes for the stress test, because the window code fails quietly.
Two carry the rating 2,300 and one carries 2,400. The first slides a window in Mo's order. The second splits the events by time. The last adds time to Mo's order as a third coordinate.
For each problem, write two lines before you code: what the state holds between two questions, and how far it moves. If the state cannot move cheaply, look for a split by time instead of a sort.
Checkpoint · Mo's algorithm and offline tricks
Q1/5 Why can a problem be solved with Mo's algorithm only when the questions are known in advance?
Answer: B
The work is the distance the window pointers travel. Choosing the order that makes this distance small needs every question up front.
Q2/5 With a block of 3, which of these ranges comes first in Mo's order: (1,2), (2,7) or (0,8)?
Answer: C
Left ends 0, 1 and 2 are all in block 0, which goes by right end upwards: 2, then 7, then 8.
Q3/5 A moving window starts empty. Which values should the pointers start with?
Answer: C
An empty window has the right pointer one step before the left pointer. Starting at right = 0 claims that position 0 is inside, and the range [0, 0] returns 0 for a log of one term.
Q4/5 The terms are 1, 1, 2, and the window moves from the range 0 to 1 to the range 1 to 2. Why does a presence flag per term give 1 for the second range, and not 2?
Answer: B
A count drops to 0 only when the last copy leaves. A flag is cleared by the first copy that leaves, so the second range loses the term 1.
Q5/5 An audit question counts earlier transactions under two limits, and there are 40,000 events. What does a split by time with a Fenwick tree cost, compared with scanning all pairs?
Answer: B
A split by time takes about n log² n steps, which is 9,348,566 for 40,000 events. Scanning the earlier events for each question costs 40,000² / 2 = 800,000,000.
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.