Practice › Graphs
Network Delay Time
Medium · Graphs · Asked at Amazon, Google, Microsoft, Uber
A signal is sent from node k through directed edges; edge u v w carries it from u to v in w time units. Print the time when all n nodes have received the signal, or -1 if some node never receives it.
Input
First line: n m k. Next m lines: u v w.
Output
The time for the signal to reach every node, or -1.
Constraints
- 1 ≤ n ≤ 10^4
- 0 ≤ m ≤ 3 × 10^4
- 0 ≤ w ≤ 10^4
Each node first hears the signal at its shortest-path distance from k. Run Dijkstra from k; the answer is the largest distance, or −1 if any distance is infinite.
Example 1
Input
4 3 2 2 1 1 2 3 1 3 4 1
Output
2
Example 2
Input
2 1 2 1 2 1
Output
-1
Hints
- Each node first receives the signal at its shortest-path distance from k.
- Weights are non-negative — Dijkstra applies.
- All nodes have the signal when the farthest one does.
Approach
Run Dijkstra from k with a min-heap of (distance, node), skipping stale heap entries. The answer is the maximum distance over all nodes; if some node is unreachable (distance still infinite) print −1.
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);
int n, m, k;
cin >> n >> m >> k;
vector<vector<pair<int, long long>>> adj(n + 1);
for (int i = 0; i < m; i++) {
int u, v;
long long w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
}
const long long INF = LLONG_MAX;
vector<long long> dist(n + 1, INF);
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;
dist[k] = 0;
pq.push({0, k});
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 w = e.second;
if (d + w < dist[v]) {
dist[v] = d + w;
pq.push({dist[v], v});
}
}
}
long long ans = 0;
for (int i = 1; i <= n; i++) ans = max(ans, dist[i]);
cout << (ans == INF ? -1 : ans) << "\n";
return 0;
}Python solution
import heapq
import sys
data = list(map(int, sys.stdin.read().split()))
n, m, k = data[0], data[1], data[2]
adj = [[] for _ in range(n + 1)]
for i in range(m):
u, v, w = data[3 + 3 * i], data[4 + 3 * i], data[5 + 3 * i]
adj[u].append((v, w))
INF = float("inf")
dist = [INF] * (n + 1)
dist[k] = 0
pq = [(0, k)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(pq, (dist[v], v))
ans = max(dist[1:])
print(-1 if ans == INF else ans)Java solution
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;
in.nextToken();
int k = (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();
adj.get(u).add(new long[] {v, (long) in.nval});
}
long[] dist = new long[n + 1];
Arrays.fill(dist, Long.MAX_VALUE);
dist[k] = 0;
PriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
pq.add(new long[] {0, k});
while (!pq.isEmpty()) {
long[] t = pq.poll();
int u = (int) t[1];
if (t[0] > dist[u]) continue;
for (long[] e : adj.get(u)) {
int v = (int) e[0];
if (t[0] + e[1] < dist[v]) {
dist[v] = t[0] + e[1];
pq.add(new long[] {dist[v], v});
}
}
}
long ans = 0;
for (int i = 1; i <= n; i++) ans = Math.max(ans, dist[i]);
System.out.println(ans == Long.MAX_VALUE ? -1 : ans);
}
}