-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-NetworkDelayTime.cpp
More file actions
76 lines (59 loc) · 2 KB
/
Copy pathLeetCode-NetworkDelayTime.cpp
File metadata and controls
76 lines (59 loc) · 2 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#define INF 1000000
//Dijkstra
struct Graph {
vector<unordered_map<int, int>> list;
Graph(int n) {
list = vector<unordered_map<int, int>>(n+1);
}
unordered_map<int, int> get_neighbours(int u) {
return list[u];
}
void add_edge(int u, int v, int w) {
list[u][v] = w;
}
};
vector<int> shortest_path(Graph& g, int o) {
vector<int> dists(g.list.size(), INF);
dists[o] = 0;
unordered_set<int> visited;
vector<pair<int, int>> nodes;
nodes.push_back({o, 0});
push_heap(nodes.begin(), nodes.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
});
while (!nodes.empty()) {
auto w = nodes.front();
pop_heap(nodes.begin(), nodes.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
});
nodes.pop_back();
for (auto v: g.get_neighbours(w.first)) {
if (visited.count(v.first) > 0) continue;
if (dists[w.first] + v.second < dists[v.first]) {
dists[v.first] = dists[w.first] + v.second;
nodes.push_back({v.first, dists[v.first]});
push_heap(nodes.begin(), nodes.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
});
}
}
visited.insert(w.first);
}
return dists;
}
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
Graph g(N);
for (int i = 0; i < times.size(); ++i) {
g.add_edge(times[i][0], times[i][1], times[i][2]);
}
vector<int> dists = shortest_path(g, K);
for (int i = 1; i < dists.size(); ++i) {
if (dists[i] == INF) return -1;
}
int m = 0;
for (int i = 1; i < dists.size(); ++i) m = max(m, dists[i]);
return m;
}
};