Test instructions
The oil price per point of the petrol station is known (ie, the point right). The length of each road (edge right).
There is a Q question. Each inquiry contains a starting point S, a finish E, and a tank capacity.
Ask for the minimum cost to go from the starting point to the end. Assume that the output impossible is not reached, otherwise the minimum travel cost is output.
Algorithm:
The fact is to analyze state = = Feel like DP.
The most straightforward idea is to add the amount of oil needed to go to the next point at every point. But the road is different, how to deal with the problem of how much?
So think of the decomposition state. That is, a split point. Each to a point + 1 units of oil, then add this state to the queue. Also assume that the oil in the tank is now enough to reach the next point,
Updates the status and adds the new state to the priority queue.
DP[I][J] Represents the cost of J for the remaining oil in the city of first I.
To put it simply. The shortest-path algorithm for priority queue optimization is one dimension.
In order to take into account all possible states.
There are only two operations at each point: 1, add a unit of oil 2, update can go to the next point.
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include < queue> #define MAXM 10010#define maxn 1010using namespace std;struct edge{int to,val,next;} edge[maxm*2];struct node{int id,cost,oil; BOOL operator < (const node &b) const {return cost > b.cost; }};bool vis[maxn][110];int CNT,HEAD[MAXN],DP[MAXN][110],ANS,ST,ED,CAP,P[MAXN];p riority_queue<node> q;void Add (int x,int y,int z) {edge[cnt].to = y; Edge[cnt].val = Z; Edge[cnt].next = Head[x]; HEAD[X] = cnt++;} BOOL BFs () {memset (dp,0x3f,sizeof (DP)); memset (vis,0,sizeof (VIS)); while (!q.empty ()) Q.pop (); int id,oil,cost; Ans = 0; Dp[st][0] = 0; Node Now,cur,next; Now.id = st; Now.cost = 0; Now.oil = 0; Q.push (now); while (!q.empty ()) {cur = q.top (); Q.pop (); id = cur.id,oil = cur.oil,cost = Cur.cost; if (id = = ed) {ans = cost; return true; } if (Vis[id][oil]) continue; Vis[id][oil] = true; if (oil < cap) {next.id = ID; Next.cost = Cost+p[id]; Next.oil = oil+1; if (Dp[next.id][next.oil]>next.cost &&!vis[next.id][next.oil]) {Dp[next.id][next.oil ] = Next.cost; Q.push (next); }} for (int i=head[id];i!=-1;i = edge[i].next) {int u = edge[i].to; int w = edge[i].val; if (oil>=w && dp[u][oil-w]>cur.cost &&!vis[u][oil-w]) {next.oil = oil-w; next.id = u; Next.cost = Cost; Dp[u][next.oil] = Next.cost; Q.push (next); }}} return false;} int main () {int n,m,u,v,l,que; while (scanf ("%d%d", &n,&m)!=eof) {memset (head,-1,sizeof (head)); CNT = 0; for (int i=0;i<n;i++) scanf ("%d", &p[i]); for (int i=0;i<m;i++) {scanf ("%d%d%d", &u,&v,&l); Add (u,v,l); Add (v,u,l); } scanf ("%d", &que); while (que--) {scanf ("%d%d%d", &cap,&st,&ed); if (BFS ()) printf ("%d\n", ans); else printf ("impossible\n"); }} return 0;}
POJ 3635 full Tank? (DP on Graph)