Practice › Graphs
Number of Shortest Paths
Medium · Graphs · Asked at Google, Amazon, Microsoft
A city has n intersections joined by two-way roads; road u v t takes t minutes. Print the number of different ways to travel from intersection 1 to intersection n in the shortest possible time, modulo 10^9 + 7. The graph is connected.
Input
First line: n m. Next m lines: u v t.
Output
The number of shortest routes modulo 10^9 + 7.
Constraints
- 1 ≤ n ≤ 10^4
- n − 1 ≤ m ≤ 3 × 10^4
- 1 ≤ t ≤ 10^9
- no repeated roads
Run Dijkstra from node 1 and also keep ways[v]. When a shorter distance to v is found, ways[v] = ways[u]; when an equal one is found, ways[v] += ways[u]. Distances need 64-bit integers.
Example 1
Input
7 10 1 7 7 1 2 2 2 3 3 2 6 3 1 4 5 4 7 3 7 6 1 6 4 1 3 7 1 1 5 3
Output
2
Example 2
Input
2 1 2 1 10
Output
1
Hints
- First you need the shortest time to every intersection — Dijkstra.
- A shortest route to v arrives through some u with dist[u] + t = dist[v].
- So ways[v] is the sum of ways[u] over such edges, computed in order of distance.
Approach
Run Dijkstra from 1 while counting: when an edge gives v a strictly smaller distance, set ways[v] = ways[u]; when it gives an equal distance, add ways[u] (mod 10^9 + 7). Because nodes are finalised in order of distance and every road takes at least one minute, ways[u] is complete before it is passed on. Distances need 64 bits.
Complexity: O((n + m) log n) time · O(n + m) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
const long long MOD = 1000000007LL;
int n, m;
cin >> n >> m;
vector<vector<pair<int, long long>>> adj(n + 1);
for (int i = 0; i < m; i++) {
int u, v;
long long t;
cin >> u >> v >> t;
adj[u].push_back({v, t});
adj[v].push_back({u, t});
}
vector<long long> dist(n + 1, LLONG_MAX), ways(n + 1, 0);
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;
dist[1] = 0;
ways[1] = 1;
pq.push({0, 1});
while (!pq.empty()) {
auto _b = pq.top();
auto d = _b.first;
auto u = _b.second;
pq.pop();
if (d > dist[u]) continue;
for (auto &e : adj[u]) {
int v = e.first;
long long t = e.second;
if (d + t < dist[v]) {
dist[v] = d + t;
ways[v] = ways[u];
pq.push({dist[v], v});
} else if (d + t == dist[v]) {
ways[v] = (ways[v] + ways[u]) % MOD;
}
}
}
cout << ways[n] << "\n";
return 0;
}Python solution
import heapq
import sys
MOD = 10**9 + 7
data = list(map(int, sys.stdin.read().split()))
n, m = data[0], data[1]
adj = [[] for _ in range(n + 1)]
for i in range(m):
u, v, t = data[2 + 3 * i], data[3 + 3 * i], data[4 + 3 * i]
adj[u].append((v, t))
adj[v].append((u, t))
INF = float("inf")
dist = [INF] * (n + 1)
ways = [0] * (n + 1)
dist[1], ways[1] = 0, 1
pq = [(0, 1)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, t in adj[u]:
if d + t < dist[v]:
dist[v] = d + t
ways[v] = ways[u]
heapq.heappush(pq, (dist[v], v))
elif d + t == dist[v]:
ways[v] = (ways[v] + ways[u]) % MOD
print(ways[n])Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
final long MOD = 1000000007L;
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<long[]>> adj = new ArrayList<>();
for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
for (int i = 0; i < m; i++) {
in.nextToken();
int u = (int) in.nval;
in.nextToken();
int v = (int) in.nval;
in.nextToken();
long t = (long) in.nval;
adj.get(u).add(new long[] {v, t});
adj.get(v).add(new long[] {u, t});
}
long[] dist = new long[n + 1], ways = new long[n + 1];
Arrays.fill(dist, Long.MAX_VALUE);
dist[1] = 0;
ways[1] = 1;
PriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
pq.add(new long[] {0, 1});
while (!pq.isEmpty()) {
long[] top = pq.poll();
int u = (int) top[1];
long d = top[0];
if (d > dist[u]) continue;
for (long[] e : adj.get(u)) {
int v = (int) e[0];
if (d + e[1] < dist[v]) {
dist[v] = d + e[1];
ways[v] = ways[u];
pq.add(new long[] {dist[v], v});
} else if (d + e[1] == dist[v]) {
ways[v] = (ways[v] + ways[u]) % MOD;
}
}
}
System.out.println(ways[n]);
}
}Solve Number of Shortest Paths online · All practice problems