A car with a limited tank is driving on a diagram. Each unit of length consumes one unit of oil, and each point on the diagram can be refueled, however, they all have their own unit fees. What is the minimum cost for driving from the start point to the end point?
This question naturally comes to the figure DP and uses the shortest circuit to transfer the equation:
- DP [u] [c] indicates the minimum cost of the current U-point fuel tank with a unit of C oil
However, I am t really bad, because during the transfer, I add more or less oil to each node through enumeration, so that each State is for an enumeration, the entire time complexity must be multiplied by the transfer cost, that is, the maximum tank capacity...
In fact, status DP [u] [c] only needs to be transferred to two directions:
- Transfer to DP [u] [C + 1], that is, adding a unit of oil to the original site
- To DP [v] [C-W (u, v)] (u, v) ε E and w (u, v) <= C), the node is directed to the next node.
In addition, you can use the spfa to run the Tle command and Dijkstra command to stabilize the AC by 1000 × 100 States.
1 #include<cstdio> 2 #include<cstring> 3 #include<queue> 4 #include<algorithm> 5 using namespace std; 6 #define INF (1<<30) 7 #define MAXN 1111 8 #define MAXM 111111 9 10 struct Edge{11 int v,w,next;12 }edge[MAXM<<1];13 int NE,head[MAXN];14 void addEdge(int u,int v,int w){15 edge[NE].v=v; edge[NE].w=w; edge[NE].next=head[u];16 head[u]=NE++;17 }18 19 int vs,vt,cap;20 int price[MAXN],d[MAXN][111];21 bool vis[MAXN][111];22 23 struct Node{24 int u,w,d;25 Node(int _u=0,int _w=0,int _d=0):u(_u),w(_w),d(_d){}26 bool operator<(const Node &nd)const{27 return nd.d<d;28 }29 };30 31 int dijkstra(){32 memset(d,127,sizeof(d));33 memset(vis,0,sizeof(vis));34 priority_queue<Node> que;35 for(int i=0; i<=cap; ++i){36 d[vs][i]=price[vs]*i;37 que.push(Node(vs,i,d[vs][i]));38 }39 while(!que.empty()){40 Node nd=que.top(); que.pop();41 if(nd.u==vt) return nd.d;42 if(vis[nd.u][nd.w]) continue;43 vis[nd.u][nd.w]=1;44 if(nd.w<cap && d[nd.u][nd.w+1]>d[nd.u][nd.w]+price[nd.u]){45 d[nd.u][nd.w+1]=d[nd.u][nd.w]+price[nd.u];46 que.push(Node(nd.u,nd.w+1,d[nd.u][nd.w+1]));47 }48 for(int i=head[nd.u]; i!=-1; i=edge[i].next){49 int v=edge[i].v;50 if(edge[i].w>nd.w) continue;51 int nw=nd.w-edge[i].w;52 if(d[v][nw]>d[nd.u][nd.w]){53 d[v][nw]=d[nd.u][nd.w];54 que.push(Node(v,nw,d[v][nw]));55 }56 }57 }58 return INF;59 }60 61 int main(){62 int n,m,q,a,b,c;63 scanf("%d%d",&n,&m);64 for(int i=0; i<n; ++i){65 scanf("%d",price+i);66 }67 memset(head,-1,sizeof(head));68 while(m--){69 scanf("%d%d%d",&a,&b,&c);70 addEdge(a,b,c);71 addEdge(b,a,c);72 }73 scanf("%d",&q);74 while(q--){75 scanf("%d%d%d",&cap,&vs,&vt);76 int res=dijkstra();77 if(res==INF) puts("impossible");78 else printf("%d\n",res);79 }80 return 0;81 }
Poj3635 full tank? (DP + Dijkstra)