题意
题解
设当前所在城市为 v v v,所剩汽油为 f l fl fl,使用二元组 ( v , f l ) (v,fl) (v,fl) 表示每一个状态。设从起始状态 ( s , 0 ) (s,0) (s,0) 达到状态 ( v , f l ) (v,fl) (v,fl) 的最小花费为 d i s [ v ] [ f l ] dis[v][fl] dis[v][fl],那么有状态转移 { d i s [ v ] [ f l + 1 ] = m i n ( d i s [ v ] [ f l + 1 ] , d i s [ v ] [ f l ] + p v ) f l < c d i s [ u ] [ f l − d ] = m i n ( d i s [ u ] [ f l − d ] , d i s [ v ] [ f l ] ) f l ≥ d , e ( u , v , d ) ∈ E \begin{cases} dis[v][fl+1]=min(dis[v][fl+1], dis[v][fl] + p_v) & fl<c\\ dis[u][fl-d]=min(dis[u][fl-d], dis[v][fl]) & fl\geq d,\ e(u,v,d)\in E \\ \end{cases} {dis[v][fl+1]=min(dis[v][fl+1],dis[v][fl]+pv)dis[u][fl−d]=min(dis[u][fl−d],dis[v][fl])fl<cfl≥d, e(u,v,d)∈E 这个状态转移是有后效性的。考虑到花费的单调不减性,进行优先队列 B F S BFS BFS,不断使用当前最小花费的状态进行拓展,直到取出 v v v 为 e e e 的状态。
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
#define maxn 1005
#define maxc 105
struct edge
{
int v, w;
edge() {}
edge(int v, int w) : v(v), w(w) {}
};
struct node
{
int v, fl, ct;
node() {}
node(int v, int fl, int ct) : v(v), fl(fl), ct(ct){}
bool operator<(const node &b) const
{
return ct > b.ct;
}
};
int N, M, Q, P[maxn], dis[maxn][maxc];
vector<edge> G[maxn];
void solve()
{
int s, e, c;
scanf("%d%d%d", &c, &s, &e);
memset(dis, 0x3f, sizeof(dis));
dis[s][0] = 0;
priority_queue<node> q;
q.push(node(s, 0, 0));
while (!q.empty())
{
node t = q.top();
q.pop();
if (t.v == e)
{
printf("%d\n", t.ct);
return;
}
if (t.fl < c)
{
int d = t.ct + P[t.v];
if (d < dis[t.v][t.fl + 1])
dis[t.v][t.fl + 1] = d, q.push(node(t.v, t.fl + 1, d));
}
for (int i = 0; i < (int)G[t.v].size(); ++i)
{
edge &e = G[t.v][i];
if (t.fl >= e.w)
{
if (t.ct < dis[e.v][t.fl - e.w])
dis[e.v][t.fl - e.w] = t.ct, q.push(node(e.v, t.fl - e.w, t.ct));
}
}
}
puts("impossible");
}
int main()
{
scanf("%d%d", &N, &M);
for (int i = 0; i < N; ++i)
scanf("%d", P + i);
for (int i = 0; i < M; ++i)
{
int u, v, d;
scanf("%d%d%d", &u, &v, &d);
G[u].push_back(edge(v, d));
G[v].push_back(edge(u, d));
}
scanf("%d", &Q);
while (Q--)
solve();
return 0;
}