链接:
http://poj.org/problem?id=3635
题意:
给出一张图,n点m边,有一辆车想从图的一个地方到达另外一个地方,边的权值是花费的油量,每个点是一个卖油的地方,每个地方买的有价格不一样,每次只能买一单位,车的最大装油量是c,求初始点到终止点的最小花费。
思路:
dp[i][j] 表示走到i点剩余j个单位的汽油时的最小花费
然后维护一个优先队列(花费小的优先更新)。 每次有两种可扩展的状态,一是加一个单位的油,二是走向邻接点,然后不断的将状态加入优先队列中。
#include <queue>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn =1e3+7;
const int INF = 1e9;
const int maxx = 1e5+5;
struct Edge
{
int v,w,next;
}edge[maxx];
struct Node
{
int v,cost,f;//f为到该点时的剩余油量
bool operator <(const Node& a)const
{
return a.cost <cost;//按油量从小到大排列
}
};
int head[maxn],e,n,m,cap;
int dp[maxn][105],used[maxn][105],p[maxn];//used表示是否走过该种情况。 p存各点油价
int s,t,ask;
priority_queue<Node> q;
void init()
{
memset(head,-1,sizeof head);
e = 0;
}
void read()
{
for(int i=0;i<n;i++)
for(int j=0;j<=100;j++)
dp[i][j]=INF;
dp[s][0]=0;
memset(used,0,sizeof used);
while(!q.empty()) q.pop();
}
void insert(int x,int y,int w)
{
edge[e].v = y;
edge[e].w = w;
edge[e].next = head[x];
head[x] = e++;
}
int bfs()
{
Node a,b;
a.v = s,a.cost =0, a.f =0;
q.push(a);
while(!q.empty())
{
a = q.top();
q.pop();
int u = a.v;
int cost = a.cost;
int f = a.f;
used[u][f] = 1;
if(u == t) return cost;
if(f+1<=cap&&!used[u][f+1]&&dp[u][f+1]>dp[u][f]+p[u])//该点买一单位油花费更少,注意只有买油时才会增加花费
{
dp[u][f+1]=dp[u][f]+p[u];
b.v=u;
b.f=f+1;
b.cost =dp[u][f+1];
q.push(b);
}
for(int i=head[u];i!=-1;i=edge[i].next)//更新与u相连的所有点
{
int v=edge[i].v;
int w=edge[i].w;
if(f>=w&&!used[v][f-w]&&dp[v][f-w]>cost)//如果剩余油量能到下一点,并且花费更少
{
dp[v][f-w] = cost;
b.v =v;
b.f= f-w;
b.cost =dp[v][f-w];
q.push(b);
}
}
}
return -1;
}
int main()
{
int x,y,w;
scanf("%d%d",&n,&m);
init();
for(int i=0;i<n;i++)
{
scanf("%d",&p[i]);
}
while(m--)
{
scanf("%d%d%d",&x,&y,&w);
insert(x,y,w);
insert(y,x,w);
}
scanf("%d",&ask);
while(ask--)
{
scanf("%d%d%d",&cap,&s,&t);
read();
int ans=bfs();
if(ans != -1) printf("%d\n",ans);
else printf("impossible\n");
}
return 0;
}