这里显然有两个维度,f[t][i]表示使用t时刻到达i所需要的最小费用总和。我们初始化的时候将其初始化为INF,但f[0][0] = passingFees[0]。 这里需要注意,由于是双向通行,对应无向图,所以转移时也要双向转移,才能计算出最终答案。
class Solution {
private:
static constexpr int INF = INT_MAX / 2;
public:
int minCost(int maxTime, vector<vector<int>>& edges, vector<int>& passingFees) {
// f[t][i] 表示花费t时间到达i的最小费用。
int n = passingFees.size();
vector<vector<int>> f(maxTime + 1,vector<int>(n, INF));
f[0][0] = passingFees[0];
for (int t = 1; t <= maxTime; t++) {
for (auto &edge : edges) {
int a = edge[0], b = edge[1], cost = edge[2];
if (t >= cost) {
f[t][b] = min(f[t][b], f[t - cost][a] + passingFees[b]);
f[t][a] = min(f[t][a], f[t - cost][b] + passingFees[a]);
}
}
}
int res = INF;
for (int t = 1; t <= maxTime; t++) {
res = min(res, f[t][n - 1]);
}
return (res == INF ? -1 : res);
}
};