n个城市之间有m条双向路。每条路要耗费一定的油量。每个城市的油价是固定并且已经给出的。有q个询问,表示从城市s走到e,油箱的容量为c,求最便宜的方案。
dp(i,j)表示走到城市i,剩余油量为j的最小花费。然后用优先队列更新,优先更新花费小的状态。走到一座城市,要么加油,要么走向下一个城市(在油量充足的情况下)。
#include<cstdio>
#include<cstring>
#include<queue>
#define MAXN 1010
using namespace std;
struct Edge
{
int v,w,next;
}edge[20010];
int cnt,head[MAXN];
void add_edge(int u,int v,int w)
{
edge[cnt].w = w;
edge[cnt].v =v ;
edge[cnt].next = head[u];
head[u] = cnt++;
}
int n,m,p[MAXN],x,y,z,dp[MAXN][110],c,s,t;
bool vis[MAXN][110];
struct Node
{
int u,cost,oil;
Node(){}
Node(int a,int b,int c)
{u = a; cost = b; oil = c;}
bool operator <(const Node &k) const//花费小的先出队
{
return cost > k.cost;
}
};
void bfs()
{
memset(dp,0x3f,sizeof dp);
memset(vis,0,sizeof vis);
dp[s][0] = 0;
priority_queue<Node> Q;
Q.push(Node(s,0,0));
while(!Q.empty())
{
Node now = Q.top();
Q.pop();
int o = now.oil,u = now.u,cost = now.cost;
vis[u][o] = 1;
if(u == t)
{
printf("%d\n",cost);
return;
}
if(o+1 <= c&&!vis[u][o+1]&&dp[u][o]+p[u] < dp[u][o+1])//加油
{
dp[u][o+1] = dp[u][o]+p[u];
Q.push(Node(u,dp[u][o+1],o+1));
}
for(int i = head[u]; i != -1; i = edge[i].next)//走向下一个城市
{
int v = edge[i].v,w = edge[i].w;
if(o >= w&&!vis[v][o-w]&&cost < dp[v][o-w])
{
dp[v][o-w] = cost;
Q.push(Node(v,dp[v][o-w],o-w));
}
}
}
printf("impossible\n");
}
int main()
{
memset(head,-1,sizeof head);
scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++)
scanf("%d",&p[i]);
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d",&x,&y,&z);
add_edge(x,y,z);
add_edge(y,x,z);
}
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d",&c,&s,&t);
bfs();
}
}