Five graph problems rated 1,400 to 1,500 whose graph hides in a story. The move: rewrite the question so that one standard pass answers it, by reversing time or edges, searching over a prefix, or counting in order.
This tent holds five problems rated 1,400 to 1,500. None says the word graph in its first line. They speak of chat servers, depots, reports and pages. So the first step is to name the nodes and the edges, and the second is to rewrite the question into one that a standard pass can answer.
| Problem | The graph | The rewrite |
|---|---|---|
| Smallest-numbered route between chat servers | servers and two-way links | search from the target, then walk from the source |
| Regions cut off as the roads close | depots and roads | run time backwards and add roads back with union-find |
| First report that breaks the cohort plan | creatives, with same and opposite reports | 2-colour the graph, and binary search the prefix |
| Shortest loop of transfers | accounts and one-way transfers | search from each account until a transfer returns to it |
| Journeys that pass a promotion page | pages and one-way links without a cycle | count in topological order with two counts |
The loop problem is the plainest, and its search is worth tracing. A loop through start is a route that leaves start and returns. So a breadth-first search from start finds the shortest loop at the first transfer that points back to start. Trace the distances first on a small graph, with the search started at the target.
Exercise · Predict the output: Hops from the target. Six servers have the two-way links 0-1, 0-2, 1-3, 2-3, 3-4 and 2-4. This searches from server 4 and prints the hop count of servers 0 to 5, with -1 for a server that is never reached. What does it print?
n = 6
edges = [[0, 1], [0, 2], [1, 3], [2, 3], [3, 4], [2, 4]]
graph = [[] for _ in range(n)]
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
dist = [-1] * n
dist[4] = 0
queue = [4]
for u in queue:
for v in graph[u]:
if dist[v] < 0:
dist[v] = dist[u] + 1
queue.append(v)
print(*dist)Each problem here is one rewrite away from a pass you know. The rewrite is the move, and it comes from asking what is awkward in the question as it is stated.
Rewrite the question so that one standard pass answers it: reverse time or edges, search from the other end, binary search over a prefix, or count in order.
The smallest route is awkward from the source, because a search from the source meets ties early. From the target, every server has a hop count. Then you walk from the source, and at each step take the smallest neighbour that is one hop closer. That walk is the smallest route among the shortest ones.
The closing roads are awkward because union-find only adds. Run time backwards: start with the roads that never close, then add the closed roads back in reverse order. The number of regions before a road comes back is the answer right after it closed.
The reports say that two creatives must be in the same cohort or in opposite cohorts. That is a 2-colouring of a graph. To find the first report that breaks the plan, note that if the first k reports can be satisfied, so can the first k - 1. So binary search the largest k that can be satisfied.
Union-find only adds, so run time backwards: start without the closing roads, then add them back in reverse.
The loop problem needs no rewrite. A breadth-first search from each account finds the shortest loop through it at the first transfer back to the start.
Exercise · Find the bug: The loop one transfer short. This returns the number of transfers in the shortest loop through one account, or -1. It searches from the account, level by level. Which line is wrong?
def shortest_loop_through(n, transfers, start):
sends = [[False] * n for _ in range(n)]
for a, b in transfers:
sends[a][b] = True
dist = [-1] * n
dist[start] = 0
queue = [start]
for u in queue:
for v in range(n):
if not sends[u][v]:
continue
if v == start:
return dist[u]
if dist[v] < 0:
dist[v] = dist[u] + 1
queue.append(v)
return -1Counting journeys is the last rewrite. A journey from page 0 to the last page may pass a promotion page, and the count can be huge. Count in topological order and carry two numbers for each page: all journeys into it, and those that have already passed a promotion page. On a promotion page, every journey into it has passed one.
The Academy lessons Graph traversal, Cycles and bipartite, Union-find and Topological sort taught each pass on a drawn graph. In a contest the graph is a story, and you do the naming and the rewriting yourself.
Three things change. You name the nodes and the edges from the text, including what an edge means: a link, a report, a transfer. You choose the pass from the limits, since a search from every node costs n times a pass. And you watch the counts, because the number of journeys grows faster than any integer type, so the statement asks for it modulo a prime.
The counting rewrite has a tempting shortcut. To count the journeys that pass a promotion page, multiply the journeys into each promotion page by the journeys out of it, and add up. A journey that passes two promotion pages is then counted twice.
Take the pages 0 to 3 with the links 0-1, 1-2, 2-3, 0-2 and 1-3, and the promotion pages 1 and 2. Three journeys exist and all pass a promotion page, but the shortcut adds up to 4.
Journeys into a page times journeys out of it counts a journey once per promotion page it passes.
Exercise · Break it: The journey that is counted twice. Journeys run from page 0 to page n - 1 over one-way links with no cycle. This counts the journeys that pass at least one promotion page by adding, for each promotion page, the journeys into it times the journeys out of it. Find an input where it is wrong.
def promo_journeys(n, links, promo):
graph = [[] for _ in range(n)]
for a, b in links:
graph[a].append(b)
def ways(u, v):
if u == v:
return 1
return sum(ways(w, v) for w in graph[u])
return sum(ways(0, p) * ways(p, n - 1) for p in promo)| Limit | What it tells you |
|---|---|
| 500 accounts and 2,000 transfers | a search from every account: 500 × 2,500 = 1,250,000 steps |
| 20,000 reports | 15 steps of binary search, each a pass over at most 40,000 entries |
| 10^5 depots and 10^5 roads | run time backwards: each road is added once |
| 10^5 pages and 2 × 10^5 links | counts of journeys are huge: take them modulo 1,000,000,007 |
The full treatment is in Fast I/O and stress testing. Here the first line holds the accounts and the transfers, and each transfer is a pair. Read all the numbers at once and build the neighbour lists from them.
import sys
def main():
data = sys.stdin.buffer.read().split()
n, m = int(data[0]), int(data[1])
graph = [[] for _ in range(n)]
for k in range(m):
graph[int(data[2 + 2 * k])].append(int(data[3 + 2 * k]))
best = n + 1
for start in range(n):
dist = [-1] * n
dist[start] = 0
queue = [start]
for u in queue:
for v in graph[u]:
if v == start:
best = min(best, dist[u] + 1)
elif dist[v] < 0:
dist[v] = dist[u] + 1
queue.append(v)
sys.stdout.write(str(best if best <= n else -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;
in.nextToken();
int m = (int) in.nval;
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
for (int k = 0; k < m; k++) {
in.nextToken();
int a = (int) in.nval;
in.nextToken();
int b = (int) in.nval;
graph.get(a).add(b);
}
int best = n + 1;
for (int start = 0; start < n; start++) {
int[] dist = new int[n];
Arrays.fill(dist, -1);
dist[start] = 0;
int[] queue = new int[n];
int head = 0, tail = 0;
queue[tail++] = start;
while (head < tail) {
int u = queue[head++];
for (int v : graph.get(u)) {
if (v == start) best = Math.min(best, dist[u] + 1);
else if (dist[v] < 0) { dist[v] = dist[u] + 1; queue[tail++] = v; }
}
}
}
System.out.println(best <= n ? best : -1);
}
}#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<vector<int>> graph(n);
for (int k = 0; k < m; k++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
}
int best = n + 1;
for (int start = 0; start < n; start++) {
vector<int> dist(n, -1), queue = {start};
dist[start] = 0;
for (size_t head = 0; head < queue.size(); head++) {
int u = queue[head];
for (int v : graph[u]) {
if (v == start) best = min(best, dist[u] + 1);
else if (dist[v] < 0) { dist[v] = dist[u] + 1; queue.push_back(v); }
}
}
}
cout << (best <= n ? best : -1) << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
const m = data[1];
const graph = Array.from({ length: n }, () => []);
for (let k = 0; k < m; k++) graph[data[2 + 2 * k]].push(data[3 + 2 * k]);
let best = n + 1;
for (let start = 0; start < n; start++) {
const dist = new Array(n).fill(-1);
dist[start] = 0;
const queue = [start];
for (let head = 0; head < queue.length; head++) {
const u = queue[head];
for (const v of graph[u]) {
if (v === start) best = Math.min(best, dist[u] + 1);
else if (dist[v] < 0) { dist[v] = dist[u] + 1; queue.push(v); }
}
}
}
process.stdout.write((best <= n ? best : -1) + "\n");On the sample of 4 accounts with the transfers 0-1, 1-2, 2-0, 2-3 and 3-1, all four programs print 3.
The slow twin follows walks of exactly 1, 2, 3 and more transfers from each account, and stops at the first length that returns to the start. It is slow, and you can check it by reading it.
import random
from fast import shortest_transfer_loop
from slow import shortest_transfer_loop as slow_loop
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 7)
transfers = [[rng.randrange(n), rng.randrange(n)] for _ in range(rng.randint(0, 10))]
if shortest_transfer_loop(n, transfers) != slow_loop(n, transfers):
print("different at", n, transfers)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Return the distance without the final plus 1, and the first seed already fails. With 7 accounts and the transfers 6-3, 0-2, 4-3, 3-6, 6-2 and 3-2, it returns 1 instead of 2.
At this band the passes are standard and the rewrite is the work. Name the nodes and the edges in one line, then name the rewrite in another, before you code. Aim for about 25 minutes a problem.
The first three rewrite the question: a search from the target, time run backwards, and a binary search over a prefix. The fourth is a search from every account. The last counts in topological order with two numbers.
For each problem, write what a node and an edge are, and the rewrite, in two lines before you code. Then write the slow twin on tiny graphs and stress test.
Checkpoint · Graph search for contests
Q1/5 You need the smallest-numbered route among all shortest routes between two servers. Where do you search from first?
Answer: B
With the hop counts to the target, you walk from the source and take the smallest neighbour that is one hop closer. That walk is the smallest of the shortest routes.
Q2/5 Roads close in the order 3, 1, 2. In which order do you add them back with union-find?
Answer: B
Time runs backwards, so the road that closed last comes back first. Start with the roads that never close.
Q3/5 A search from an account reaches account u at distance 2, and u has a transfer back to the start. How many transfers has the loop?
Answer: B
The distance counts the transfers from the start to u. The transfer back to the start is one more.
Q4/5 Why can you binary search the largest k for which the first k reports can be satisfied?
Answer: B
Dropping a report removes a constraint. So the satisfiable prefixes form one block, and the search finds where it ends.
Q5/5 A journey passes two promotion pages. How often does 'journeys into the page times journeys out of it', added over the promotion pages, count it?
Answer: B
Each promotion page that the journey passes counts it once. For 4 pages and the promotion pages 1 and 2 there are 3 journeys and the sum gives 4.
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.