-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
minimum-cost-to-buy-apples.cpp
45 lines (42 loc) · 1.53 KB
/
minimum-cost-to-buy-apples.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
// Time: O(n * rlogn), r = len(roads)
// Space: O(n)
// dijkstra's algorithm
class Solution {
public:
vector<long long> minCost(int n, vector<vector<int>>& roads, vector<int>& appleCost, int k) {
static const int INF = numeric_limits<int>::max();
vector<vector<pair<int, int>>> adj(n);
for (const auto& r : roads) {
adj[r[0] - 1].emplace_back(r[1] - 1, r[2]);
adj[r[1] - 1].emplace_back(r[0] - 1, r[2]);
}
const auto& dijkstra = [&](int start) {
vector<long long> best(size(adj), INF);
best[start] = 0;
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> min_heap;
min_heap.emplace(0, start);
while (!empty(min_heap)) {
const auto [curr, u] = min_heap.top(); min_heap.pop();
if (best[u] < curr) {
continue;
}
for (const auto& [v, w] : adj[u]) {
if (best[v] - curr <= w) {
continue;
}
best[v] = curr + w;
min_heap.emplace(curr + w, v);
}
}
return best;
};
vector<long long> result(n, INF);
for (int u = 0; u < n; ++u) {
const auto& best = dijkstra(u);
for (int v = 0; v < n; ++v) {
result[u] = min(result[u], appleCost[v] + (k + 1) * best[v]);
}
}
return result;
}
};