-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkDelayTime.cpp
60 lines (47 loc) · 1.48 KB
/
NetworkDelayTime.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
struct Edge {
int dest;
int weight;
};
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
vector<Edge>* graph = new vector<Edge>[n];
for (int i = 0; i < times.size(); i++) {
int u_i = times[i][0] - 1;
int v_i = times[i][1] - 1;
int w_i = times[i][2];
graph[u_i].push_back({v_i, w_i});
}
int* dist = new int[n](); // shortest path to every node
fill(dist, dist + n, INT_MAX);
// {dist[node], node}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
dist[k - 1] = 0;
pq.push({dist[k - 1], k - 1});
while (!pq.empty()) {
int dist_v = pq.top().first;
int v = pq.top().second;
pq.pop();
if (dist_v > dist[v]) { // only first visit will be considered
continue;
}
for (int i = 0; i < graph[v].size(); i++) {
int u = graph[v][i].dest;
int weight = graph[v][i].weight;
int new_dist = dist[v] + weight;
if (new_dist < dist[u]) {
dist[u] = new_dist;
pq.push({dist[u], u});
}
}
}
int delay = 0;
for (int i = 0; i < n; i++) {
delay = max(delay, dist[i]);
}
if (delay == INT_MAX) {
return -1;
}
return delay;
}
};