Question: Give the oil price of n locations and each location, have m edges, and give the length of each edge. 1 unit of gasoline can go through 1 km, and the tank capacity is c. At the initial point of s, the oil in the tank is 0, and the minimum cost from s to t is calculated.
Solution: define the State d [I] [j] to indicate the minimum cost of arrival location I and the fuel tank contains j units of oil. There are two methods for transferring status:
1. obtain all the statuses of each vertex.
2. do not find the status of each vertex, but refuel every unit.
For the first method, it will time out because there are too many States for each vertex, but there are only a few available States. Therefore, you must use the second method to transfer the state.
After confirming the status transfer, I can use dijkstra + heap for optimization.
Code:
#include
#include
#include
#include
#include
using namespace std;#define maxn 1010#define INF 0xfffffffstruct node{ int u , fle , d; bool operator < (const node& chs) const { return d > chs.d; }};struct edge{ int u , d; int next;}grap[20010];int n , m;int ci[maxn] , pre[maxn][110];int head[maxn];int d[maxn][110];int s , t , c;void init(){ memset(head , -1 , sizeof(head));}void add_edge(int x , int y , int z , int &k){ grap[k].u = y; grap[k].d = z; grap[k].next = head[x]; head[x] = k++; grap[k].u = x; grap[k].d = z; grap[k].next = head[y]; head[y] = k++;}int dijkstra(){ priority_queue
q; memset(pre , 0 , sizeof(pre)); int i ; memset(d , -1 , sizeof(d)); d[s][0] = 0; node f , e; e.u = s; e.fle = e.d = 0; q.push(e); while(!q.empty()) { e = q.top(); q.pop(); if(e.u == t) return e.d; for(i = head[e.u]; i != -1 ; i = grap[i].next) { if(e.fle >= grap[i].d) { int fuel=e.fle-grap[i].d; if(d[grap[i].u][fuel]==-1||d[grap[i].u][fuel]>e.d) { f.u = grap[i].u; f.fle = fuel; f.d = e.d; d[grap[i].u][fuel] = e.d; // printf("tt.u %d cost %d fuel %d\n",tt.u,tt.fuel,tt.cost); q.push(f); } } if(e.fle < c) { if(d[e.u][e.fle+1]==-1||d[e.u][e.fle+1]>e.d+ci[e.u]) { f.u = e.u; f.fle = e.fle+1; f.d = e.d+ci[e.u]; d[e.u][f.fle] = e.d+ci[e.u]; // printf("tt.u %d cost %d fuel %d\n",tt.u,tt.fuel,tt.cost); q.push(f); } } } } return -1;}int main(){ while(scanf("%d %d" , &n , &m) != EOF) { init(); int i , x , y , z; int k = 0; for(i = 0; i < n; i++) scanf("%d" , &ci[i]); for(i = 0; i < m; i++) { scanf("%d %d %d" , &x , &y , &z); add_edge(x , y , z , k); } int p; scanf("%d" , &p); for(i = 1; i <= p; i++) { scanf("%d %d %d" , &c , &s , &t); x = dijkstra(); if(x == -1) cout<<"impossible"<