-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0787-cheapest-flights-within-k-stops.cpp
63 lines (54 loc) · 1.96 KB
/
0787-cheapest-flights-within-k-stops.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
61
62
63
// class Solution {
// public:
// int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
// unordered_map<int, vector<pair<int, int>>> g;
// for(auto flight: flights) {
// auto from = flight[0], to = flight[1], price = flight[2];
// g[from].push_back({to, price});
// }
// priority_queue<pair<int, int>, vector<pair<int, int>>, >
// }
// };
// typedef tuple<int,int,int> ti;
// class Solution {
// public:
// int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
// vector <vector<pair<int,int>>> vp(n);
// for(const auto& f: flights) vp[f[0]].emplace_back(f[1], f[2]);
// priority_queue<ti, vector<ti>, greater<ti>> pq;
// pq.emplace(0, src, K + 1);
// while(!pq.empty()) {
// auto [cost, u, stops] = pq.top();
// pq.pop();
// if (u == dst) return cost;
// if (!stops) continue;
// for (auto to: vp[u]) {
// auto [v,w] = to;
// pq.emplace(cost + w, v, stops - 1);
// }
// }
// return -1;
// }
// };
class Solution {
public:
template<typename T_a3, typename T_vector>
void bellman_ford(T_a3 &g, T_vector &dist, int src, int mx_edges) {
dist[src] = 0;
for (int i = 0; i <= mx_edges; i++) {
T_vector ndist = dist;
for (auto x : g) {
auto [from, to, cost] = x;
ndist[to] = min(ndist[to], dist[from] + cost);
}
dist = ndist;
}
}
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
vector<array<int, 3>> g;
vector<int> cost(n, 1e9);
for (auto f : flights) g.push_back({f[0], f[1], f[2]});
bellman_ford(g, cost, src, k);
return cost[dst] == 1e9 ? -1 : cost[dst];
}
};