[LeetCode] Minimum Cost to Reach Destination in Time

1928. Minimum Cost to Reach Destination in Time

There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.

Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j.

In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities).

Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.

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
class Solution {
vector<vector<pair<int,int>>> buildGraph(vector<vector<int>>& edges, int n) {
vector<vector<int>> graph(n, vector<int>(n, INT_MAX));
for(auto e : edges) {
graph[e[0]][e[1]] = min(graph[e[0]][e[1]], e[2]);
graph[e[1]][e[0]] = min(graph[e[1]][e[0]], e[2]);
}

vector<vector<pair<int,int>>> compressGraph(n);
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(graph[i][j] == INT_MAX) continue;
compressGraph[i].push_back({j, graph[i][j]});
compressGraph[j].push_back({i, graph[i][j]});
}
}
return compressGraph;
}
int bfs(vector<vector<pair<int,int>>>& g, int limit, vector<int>& fee) {
int n = fee.size();

priority_queue<array<int, 3>, vector<array<int, 3>>, greater<array<int, 3>>> pq;
vector<int> cost(n, INT_MAX);
cost[0] = fee[0];

pq.push({0, fee[0], 0});
while(!pq.empty()) {
auto [time, feeSum, node] = pq.top(); pq.pop();
if(cost[node] < feeSum) continue;
cost[node] = feeSum;
for(auto [near, weight] : g[node]) {
if(time + weight > limit) continue;
if(feeSum + fee[near] > cost[near]) continue;
pq.push({time + weight, feeSum + fee[near], near});
}
}

return cost.back() == INT_MAX ? -1 : cost.back();
}
public:
int minCost(int maxTime, vector<vector<int>>& edges, vector<int>& passingFees) {
vector<vector<pair<int,int>>> g = buildGraph(edges, passingFees.size());

return bfs(g, maxTime, passingFees);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/11/PS/LeetCode/minimum-cost-to-reach-destination-in-time/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.