1
typedef pair<int, pair<int, int>> pii;5
int minCost(int maxTime, vector<vector<int>> &edges, vector<int> &passingFees) {6
int n = passingFees.size();8
// state of dp(i,j) : stores the min cost to reach city 'i' in 'j' max time;9
int dp[n][maxTime + 1];11
// without using another array for time will result in TLE since it will12
// explore more paths, hence using another array that stores the min time13
// the city was discovered. This improves the TC to a huge extent as it17
for (int i = 0; i < n; i++) {19
for (int j = 0; j <= maxTime; j++) {24
dp[0][0] = passingFees[0];26
vector<vector<int>> adj[n];27
for (auto x : edges) {28
adj[x[0]].push_back({x[1], x[2]});29
adj[x[1]].push_back({x[0], x[2]});32
// first priority is to minimise the cost associated with the path, {cost,34
priority_queue<pii, vector<pii>, greater<pii>> minHeap;35
minHeap.push({passingFees[0], {0, 0}});37
while (!minHeap.empty()) {38
auto top = minHeap.top();41
int u = top.second.first;42
int time = top.second.second;45
if (u == n - 1) return cost;49
for (auto x : adj[u]) {50
// this is the pruning part, where we are only exploring paths that can51
// be reached earlier than52
// the time already required.53
if (time + x[1] < ttime[x[0]]) {54
if (time + x[1] <= maxTime) {55
// now we are checking if the cost to reach the neighbor is less56
// than the already minimum cost, denoted by dp[x[0]][time+x[1]],57
// denoting min cost to reach x[0] in 'time+x[1]' max time.58
if (cost + passingFees[x[0]] < dp[x[0]][time + x[1]]) {59
dp[x[0]][time + x[1]] = cost + passingFees[x[0]];60
ttime[x[0]] = time + x[1];61
minHeap.push({dp[x[0]][time + x[1]], {x[0], time + x[1]}});