Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7866 | Accepted: 2547 |
Description
After going through the receipts from your car trip through Europe this summer, you realised that the gas prices varied between the cities you visited. Maybe you could have saved some money if you were a bit more clever about where you filled your fuel?
To help other tourists (and save money yourself next time), you want to write a program for finding the cheapest way to travel between cities, filling your tank on the way. We assume that all cars use one unit of fuel per unit of distance, and start with an empty gas tank.
Input
The first line of input gives 1 ≤ n ≤ 1000 and 0 ≤ m ≤ 10000, the number of cities and roads. Then follows a line with n integers 1 ≤ pi ≤ 100, where pi is the fuel price in the ith city. Then follow m lines with three integers 0 ≤ u, v < n and 1 ≤ d ≤ 100, telling that there is a road between u and v with length d. Then comes a line with the number 1 ≤ q ≤ 100, giving the number of queries, and q lines with three integers 1 ≤ c ≤ 100, s and e, where c is the fuel capacity of the vehicle, s is the starting city, and e is the goal.
Output
For each query, output the price of the cheapest trip from s to e using a car with the given capacity, or "impossible" if there is no way of getting from s to e with the given car.
Sample Input
5 5 10 10 20 12 13 0 1 9 0 2 8 1 2 1 1 3 11 2 3 7 2 10 0 3 20 1 4
Sample Output
170 impossible
思路:用优先队列来维护,dp有两种状态,一种是加1容量的油,另一种是不加油直接跑到下一个点
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
const int inf=0x3f3f3f3f;
const int N=10000+10;
struct edge
{
int v,w,next;
}e[N<<2];
int dp[1010][105];
int head[N<<2];
bool vis[1010][105];
int num;
int n,m,q;
int w[1010];
void init()
{
memset(head,-1,sizeof(head));
num=0;
}
void addedge(int u,int v,int w)
{
e[num].v=v;
e[num].w=w;
e[num].next=head[u];
head[u]=num++;
}
struct node
{
int v,c,f;
bool operator<(const node &a)const{
return a.c<c;
}
};
int bfs(int c,int s,int t)
{
memset(vis,0,sizeof(vis));
memset(dp,inf,sizeof(dp));
priority_queue<node>Q;
node a,b;
a.v=s;
a.f=0;
a.c=0;
Q.push(a);
dp[s][0]=0;
while(!Q.empty())
{
a=Q.top();
Q.pop();
int u=a.v;
int co=a.c;
int f=a.f;
vis[u][f]=1;
if(u==t)return co;
if(f+1<=c&&!vis[u][f+1]&&dp[u][f+1]>dp[u][f]+w[u])
{
dp[u][f+1]=dp[u][f]+w[u];
b.v=u;
b.f=f+1;
b.c=dp[u][f+1];
Q.push(b);
}
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].v;
int w1=e[i].w;
if(f>=w1&&!vis[v][f-w1]&&dp[v][f-w1]>co)
{
dp[v][f-w1]=co;
b.v=v;
b.f=f-w1;
b.c=dp[v][f-w1];
Q.push(b);
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
init();
for(int i=0;i<n;i++)
scanf("%d",&w[i]);
for(int i=0;i<m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
addedge(u,v,w);
addedge(v,u,w);
}
scanf("%d",&q);
while(q--)
{
int c,s,t;
scanf("%d%d%d",&c,&s,&t);
int ans=bfs(c,s,t);
if(ans!=-1)printf("%d\n",ans);
else printf("impossible\n");
}
}
return 0;
}