forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reachable-nodes-in-subdivided-graph.cpp
46 lines (45 loc) · 1.6 KB
/
reachable-nodes-in-subdivided-graph.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
// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|),
// if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)
// Space: O(|E| + |V|) = O(|E|)
class Solution {
public:
int reachableNodes(vector<vector<int>>& edges, int M, int N) {
using P = pair<int, int>;
vector<vector<P>> adj(N);
for (const auto& edge: edges) {
int u = edge[0], v = edge[1], w = edge[2];
adj[u].emplace_back(v, w);
adj[v].emplace_back(u, w);
}
unordered_map<int, int> best;
best[0] = 0;
unordered_map<int, unordered_map<int, int>> count;
int result = 0;
priority_queue<P, vector<P>, greater<P>> min_heap;
min_heap.emplace(0, 0);
while (!min_heap.empty()) {
int curr_total, u;
tie(curr_total, u) = min_heap.top(); min_heap.pop();
if (best.count(u) && best[u] < curr_total) {
continue;
}
++result;
for (const auto& kvp: adj[u]) {
int v, w;
tie(v, w) = kvp;
count[u][v] = min(w, M - curr_total);
int next_total = curr_total + w + 1;
if (next_total <= M &&
(!best.count(v) || next_total < best[v])) {
best[v] = next_total;
min_heap.emplace(next_total, v);
}
}
}
for (const auto& edge: edges) {
int u = edge[0], v = edge[1], w = edge[2];
result += min(w, count[u][v] + count[v][u]);
}
return result;
}
};