Cities are joined by one-way flights, each with a price. Find the cheapest journey from one city to another that makes at most k stops in between.
Return -1 if no such journey exists. A direct flight makes zero stops.
findCheapestPrice(4, {{0,1,100},{1,2,100},{2,0,100},{1,3,600},{2,3,200}}, 0, 3, 1)
The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.
| 1 | int findCheapestPrice(int n, const vector<vector<int>>& flights, |
| 2 | int from, int to, int k) { |
| 3 | |
| 4 | vector<int> best(n, INT_MAX); |
| 5 | |
| 6 | for (int round = 0; round < k; round++) { |
| 7 | |
| 8 | vector<int> next = best; |
| 9 | |
| 10 | for (const auto& f : flights) { |
| 11 | |
| 12 | if (best[f[0]] == INT_MAX) { |
| 13 | continue; |
| 14 | } |
| 15 | |
| 16 | int cost = best[f[0]] + f[2]; |
| 17 | next[f[1]] = min(next[f[1]], cost); |
| 18 | } |
| 19 | |
| 20 | best = next; |
| 21 | } |
| 22 | |
| 23 | if (best[to] == INT_MAX) { |
| 24 | return -1; |
| 25 | } |
| 26 | |
| 27 | return best[to]; |
| 28 | } |
| 1 | int findCheapestPrice(int n, const vector<vector<int>>& flights, |
| 2 | int from, int to, int k) { |
| 3 | |
| 4 | vector<int> best(n, INT_MAX); |
| 5 | |
| 6 | for (int round = 1; round <= k; round++) { |
| 7 | |
| 8 | vector<int> next = best; |
| 9 | |
| 10 | for (const auto& f : flights) { |
| 11 | |
| 12 | if (best[f[0]] == INT_MAX) { |
| 13 | continue; |
| 14 | } |
| 15 | |
| 16 | int cost = best[f[0]] + f[2]; |
| 17 | next[f[1]] = min(next[f[1]], cost); |
| 18 | } |
| 19 | |
| 20 | best = next; |
| 21 | } |
| 22 | |
| 23 | if (best[to] == INT_MAX) { |
| 24 | return -1; |
| 25 | } |
| 26 | |
| 27 | return best[to]; |
| 28 | } |
| 1 | int findCheapestPrice(int n, const vector<vector<int>>& flights, |
| 2 | int from, int to, int k) { |
| 3 | |
| 4 | vector<int> best(n, INT_MAX); |
| 5 | best[from] = 0; |
| 6 | |
| 7 | for (int round = 0; round <= k; round++) { |
| 8 | |
| 9 | vector<int> next = best; |
| 10 | |
| 11 | for (const auto& f : flights) { |
| 12 | |
| 13 | if (best[f[0]] == INT_MAX) { |
| 14 | continue; |
| 15 | } |
| 16 | |
| 17 | int cost = best[f[0]] + f[2]; |
| 18 | next[f[1]] = min(next[f[1]], cost); |
| 19 | } |
| 20 | |
| 21 | best = next; |
| 22 | } |
| 23 | |
| 24 | if (best[to] == INT_MAX) { |
| 25 | return -1; |
| 26 | } |
| 27 | |
| 28 | return best[to]; |
| 29 | } |