题意:
小明现在要追讨一笔债务,已知有座城市,每个城市都有编号,城市与城市之间存在道路相连(每条道路都是双向的),经过任意一条道路需要支付费用。小明一开始位于编号为
的城市,欠债人位于编号为
的城市。小明每次从一个城市到达另一个城市需要耗时
天,而欠债人每天都会挥霍一定的钱,等到第
天后(即第
天)他就会离开城n并再也找不到了。小明必须要在他离开前抓到他(最开始为第
天),同时希望自己的行程花费和欠债人挥霍的钱的总和最小,你能帮他计算一下最小总和吗?
题解: 最短路变形,考虑除了距离外增加一个条件:价值。因为只要在天内到达即可,所以考虑在
天内到达目的地的价值越低越好,故优先队列维护的是最低价值。
考虑到到达从点到达点
的路径多条,且可能路径长度更长的价值更低,
所以这里不可以用首次到达点作为堆优化
的优化点,而是应该用价值。
即如果队头中当前该天的价值大于该天目前的价值,则无需用该状态更新其邻点了。
同时这里的优化条件必须为大于,因为初始点的价值为,队列第一个点也就是初始点,也就是
。
代码:
#include<bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int N = 1010; const int M = 20010; int h[N], e[M], ne[M], w[M], idx; void add(int a, int b, int c) { e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++; } int q[N]; int dist[N][N]; int st[N]; int n, m, k; struct Node{ int u, day, w; bool operator < (const Node &A) const { return w > A.w; } }; void dijkstra(int fir) { memset(dist, 0x3f, sizeof dist); dist[0][fir] = 0; priority_queue<Node> que; que.push({fir, 0, 0}); while(!que.empty()) { Node t = que.top(); que.pop(); int u = t.u, d = t.day; if(t.w > dist[d][u]) continue; for(int i = h[u]; i != -1; i = ne[i]) { int v = e[i]; if(d + 1 <= k && dist[d + 1][v] > dist[d][u] + w[i] + q[d + 1]) { dist[d + 1][v] = dist[d][u] + w[i] + q[d + 1]; que.push({v, d + 1, dist[d + 1][v]}); } } } } int main() { memset(h, -1, sizeof h); scanf("%d%d%d", &n, &m, &k); for(int i = 1; i <= m; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); add(a, b, c), add(b, a, c); } for(int i = 1; i <= k; i++) scanf("%d", &q[i]); dijkstra(1); int res = INF; for(int i = 1; i <= k; i++) res = min(res, dist[i][n]); if(res >= INF) res = -1; printf("%d\n", res); return 0; }