Four shortest path problems rated 1,500 to 1,600 where the route must remember something. The move: put what the route remembers into the node, then pick the pass that fits the edge costs.
This tent holds four problems rated 1,500 to 1,600. In each one the cheapest route is only part of the question. You also count the routes that tie, count the paid links, or use a coupon once. So the route has to remember something as it goes.
| Problem | Link costs | The pass | What the node remembers |
|---|---|---|---|
| Cheapest settlement route and how many tie | fees of at least 1 | Dijkstra with a heap | the fee, the number of routes, the fewest links |
| Fewest paid hops across the site | 0 or 1 | a double-ended queue | the paid count |
| Latency totals as new links come online | up to 100 services | Floyd-Warshall, then one update per link | every pair |
| Cheapest ride with one free leg | 0 to 10^9 | Dijkstra on a doubled graph | whether the coupon is used |
Start with the counting problem, because its trace shows what the node carries. When two routes reach a node with the same fee, the number of routes adds up. When a cheaper route arrives, the number of routes is replaced.
Exercise · Predict the output: The routes that tie. Five processors have the one-way links 0 to 1 (fee 2), 0 to 2 (1), 2 to 1 (1), 1 to 3 (3), 2 to 3 (4), 3 to 4 (1) and 1 to 4 (5). This finds the lowest fee from 0 to 4 and the number of routes with it. What does it print?
n = 5
links = [[0, 1, 2], [0, 2, 1], [2, 1, 1], [1, 3, 3], [2, 3, 4], [3, 4, 1], [1, 4, 5]]
INF = 10 ** 9
dist = [INF] * n
ways = [0] * n
dist[0] = 0
ways[0] = 1
done = [False] * n
for _ in range(n):
u = min((v for v in range(n) if not done[v]), key=lambda v: dist[v])
done[u] = True
for a, b, w in links:
if a == u:
if dist[u] + w < dist[b]:
dist[b] = dist[u] + w
ways[b] = ways[u]
elif dist[u] + w == dist[b]:
ways[b] += ways[u]
print(dist[4], ways[4])When the question asks for more than a distance, ask what the route must remember. Put that into the node. A node is then a pair, and the shortest path pass runs on the pairs.
Put whatever the route must remember into the node, then run the shortest path pass that fits the link costs.
The coupon problem shows it. A trip may make one leg free, so give every stop two states: coupon unused and coupon used. A normal leg keeps the layer and costs its fare.
A free leg moves from the unused layer to the used layer and costs nothing. The answer is the cheaper of the two states of the target.
Give each stop two states, coupon unused and coupon used, and let a free leg move between them.
The link costs pick the pass. Links that cost 0 or 1 need only a double-ended queue. A free link puts the next node at the front, so it is taken before any node that costs more. A paid link puts it at the back.
Positive costs need a heap, and a small graph of at most 100 nodes can use Floyd-Warshall for every pair.
New links arrive one at a time, and the total of all pairs must be reported after each. A new link of cost w between a and b helps the pair i and j only if the route uses it, in one direction or the other. Try both for every pair, which takes n squared steps per link.
Exercise · Put it in order: The total after one new link. Arrange the lines into a function that takes the table of shortest distances between all pairs of services, and a new two-way link, and returns the total latency of all pairs after the link.
def total_after_link(dist, a, b, w):
n = len(dist)
total = 0
for i in range(n):
for j in range(i + 1, n):
through = min(dist[i][a] + w + dist[b][j], dist[i][b] + w + dist[a][j])
total += min(dist[i][j], through)
return total
through = dist[i][a] + w + dist[b][j]Floyd-Warshall needs two cares. Its middle node goes in the outermost loop, because each round allows one more stop for every pair at once. With the middle node innermost, the chain 0-1-3-2 with links of cost 1 returns 1,000,000,007, as the pair 0 and 2 is never completed. The second care is a repeated link, where the table must keep the cheaper one.
Exercise · Find the bug: The repeated link that overwrites. This returns the total latency over all pairs of services after Floyd-Warshall. The links are two-way, can repeat, and connect all services. Which line is wrong?
def latency_total(n, links):
INF = 10 ** 9
dist = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for a, b, w in links:
dist[a][b] = dist[b][a] = w
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return sum(dist[i][j] for i in range(n) for j in range(i + 1, n))The Academy lesson Dijkstra taught the heap pass. Graph traversal taught a plain breadth-first search, Queues and deques the double-ended queue, and Heaps and priority queues the heap itself. This tent chooses between them and extends the node.
Three things change. The link costs choose the pass, so read them first. The node grows to hold what the route must remember. And the answer may be more than a distance: a count of routes, the fewest links among them, or the best of several states.
The pass choice has a tempting error for costs of 0 and 1. A breadth-first search that visits each node once treats every link alike and keeps the first cost it finds. A free route found later is ignored.
Take the links 0 to 2 (paid), 0 to 1 (free) and 1 to 2 (free). The search reaches 2 first by the paid link and returns 1, while the free route costs 0.
A search that visits each node once keeps the first cost it finds, so a free route found later is lost.
Exercise · Break it: The search that visits each page once. Each link is one way and is free (0) or paid (1). This finds the fewest paid links from the source to the target with a breadth-first search that visits each page once, or -1. Find an input where it is wrong.
def fewest_paid_hops(n, links, source, target):
graph = [[] for _ in range(n)]
for a, b, paid in links:
graph[a].append((b, paid))
cost = [-1] * n
cost[source] = 0
queue = [source]
for u in queue:
for v, paid in graph[u]:
if cost[v] < 0:
cost[v] = cost[u] + paid
queue.append(v)
return cost[target]| Limit | What it tells you |
|---|---|
| 50,000 processors and 100,000 links | Dijkstra: about 2,400,000 steps, and fees up to 5 × 10^13: use 64 bits |
| 10^5 pages and 2 × 10^5 links with cost 0 or 1 | a double-ended queue, linear time |
| 100 services and 100 new links | Floyd-Warshall once (10^6 steps), then 10^4 steps for each link |
| 30,000 stops and 60,000 legs | 60,000 states and 180,000 legs in the doubled graph |
The full treatment is in Fast I/O and stress testing. Here the first line holds the services and the links, and each link is three numbers. The distances are 64-bit in Java and C++.
import sys
def main():
data = sys.stdin.buffer.read().split()
n, m = int(data[0]), int(data[1])
inf = 10 ** 9
dist = [[0 if i == j else inf for j in range(n)] for i in range(n)]
for k in range(m):
a, b, w = int(data[2 + 3 * k]), int(data[3 + 3 * k]), int(data[4 + 3 * k])
dist[a][b] = min(dist[a][b], w)
dist[b][a] = min(dist[b][a], w)
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
total = sum(dist[i][j] for i in range(n) for j in range(i + 1, n))
sys.stdout.write(str(total) + "\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;
long inf = 1_000_000_000L;
long[][] dist = new long[n][n];
for (long[] row : dist) Arrays.fill(row, inf);
for (int i = 0; i < n; i++) dist[i][i] = 0;
for (int k = 0; k < m; k++) {
in.nextToken();
int a = (int) in.nval;
in.nextToken();
int b = (int) in.nval;
in.nextToken();
long w = (long) in.nval;
dist[a][b] = Math.min(dist[a][b], w);
dist[b][a] = Math.min(dist[b][a], w);
}
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
long total = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) total += dist[i][j];
System.out.println(total);
}
}#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;
const long long inf = 1000000000LL;
vector<vector<long long>> dist(n, vector<long long>(n, inf));
for (int i = 0; i < n; i++) dist[i][i] = 0;
for (int k = 0; k < m; k++) {
int a, b;
long long w;
cin >> a >> b >> w;
dist[a][b] = min(dist[a][b], w);
dist[b][a] = min(dist[b][a], w);
}
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
long long total = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) total += dist[i][j];
cout << total << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
const m = data[1];
const inf = 1e9;
const dist = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 0 : inf)));
for (let k = 0; k < m; k++) {
const a = data[2 + 3 * k], b = data[3 + 3 * k], w = data[4 + 3 * k];
dist[a][b] = Math.min(dist[a][b], w);
dist[b][a] = Math.min(dist[b][a], w);
}
for (let k = 0; k < n; k++)
for (let i = 0; i < n; i++)
for (let j = 0; j < n; j++)
dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
let total = 0;
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++) total += dist[i][j];
process.stdout.write(total + "\n");On the sample of 3 services with the links 0-1 (1), 1-2 (1) and 0-2 (5), all four programs print 4.
The slow twin recomputes all distances from scratch after every new link. It is slow, and you can check it by reading it. The generator joins the services in a chain first, so that the graph is connected.
import random
from fast import latency_totals
from slow import latency_totals as slow_totals
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(2, 6)
links = [[i, i + 1, rng.randint(1, 9)] for i in range(n - 1)]
links += [[rng.randrange(n), rng.randrange(n), rng.randint(1, 9)] for _ in range(rng.randint(0, 4))]
added = [[rng.randrange(n), rng.randrange(n), rng.randint(1, 9)] for _ in range(rng.randint(1, 4))]
if latency_totals(n, links, added) != slow_totals(n, links, added):
print("different at", n, links, added)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Update only the pair that the new link joins, and seed 3 fails. The first answer is 15 instead of 12.
At this band the passes are known, and the state is the work. Write what the node remembers in one line, and the pass in another, before you code. Aim for about 25 minutes a problem.
The first adds counts to Dijkstra. The second drops the heap for a double-ended queue, and the third computes every pair for a small graph. The last doubles the graph to remember the coupon.
For each problem, write what the node remembers and the pass in two lines before you code. Then write the slow twin on tiny graphs, which is a table of all routes, and stress test.
Checkpoint · Shortest paths for contests
Q1/5 Two routes reach a node at the same lowest fee, and the first node before it has 2 routes and the second has 1. How many cheapest routes does the node get?
Answer: B
When routes tie, their counts add. A cheaper route replaces the count. In the example processor 3 is reached at fee 5 by 3 routes.
Q2/5 A trip may use one coupon to make a leg free. How many states does each stop have?
Answer: B
A normal leg keeps the layer. A free leg moves from the unused layer to the used layer. The answer is the cheaper state of the target.
Q3/5 Links cost 0 or 1. Where does a double-ended queue put the node after a free link?
Answer: B
A free link keeps the paid count, so the node is as good as the node that was taken, and it is taken next. A paid link goes to the back.
Q4/5 Where does the middle node k go in the loops of Floyd-Warshall?
Answer: B
Each round allows one more stop for every pair. With k innermost, the chain 0-1-3-2 with links of cost 1 returns 1,000,000,007.
Q5/5 A new two-way link joins a and b. Which pairs of services can get a shorter route?
Answer: B
A pair i and j can use the new link as i to a, over the link, and b to j, or the other way round. That takes n squared steps for each new link.
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.