The main topic: There are N gas stations, each gas station oil price known, and known the size of the tank, ask whether to go from the starting point to the end, if possible, find the minimum fuel costs.
Title Analysis: Remember to do a violent search when doing this problem, not difficult. But this is done with the Dijkstra algorithm, the time complexity is not ideal, almost timeout (1.9s, the limit is 2s). It's much quicker to do it with BFS.
The code is as follows:
# include<iostream># include<cstdio># include<queue># include<cstring># include< Algorithm>using namespace std;# define REP (i,s,n) for (int i=s;i<n;++i) # define CL (b) memset (A,b,sizeof (a)) const int inf=1<<30;struct node{int u,k; Node (int _u,int _k): U (_u), K (_k) {}};const int n=1005;struct edge{int to,nxt,w;}; Edge e[n*20];int inq[n][105],dis[n][105],head[n],p[n],n,m,cnt;void Add (int u,int v,int W) {e[cnt].to=v; E[cnt].w=w; E[cnt].nxt=head[u]; head[u]=cnt++;} int Dijkstra (int c,int s,int t) {CL (inq,0); Rep (I,0,n) Rep (j,0,c+1) Dis[i][j]=inf; queue<node>q; Q.push (Node (s,0)); dis[s][0]=0; while (!q.empty ()) {Node top=q.front (); Q.pop (); int U=TOP.U,K=TOP.K; inq[u][k]=0; for (int i=head[u];i!=-1;i=e[i].nxt) {int v=e[i].to; if (K>=e[i].w&&dis[v][k-e[i].w]>dis[u][k]) {dis[v][k-e[i].w]=dis[u][k]; if (!inq[v][k-e[i].W]) {inq[v][k-e[i].w]=1; Q.push (Node (V,K-E[I].W)); }} if (K<c&&dis[u][k+1]>dis[u][k]+p[u]) {dis[u][k+1]=dis[u][k]+p[u]; if (!inq[u][k+1]) {inq[u][k+1]=1; Q.push (Node (u,k+1)); }}}} int res=inf; REP (i,0,c+1) res=min (Res,dis[t][i]); return res;} int main () {int a,b,c,query; while (~SCANF ("%d%d", &n,&m)) {cnt=0; CL (head,-1); REP (i,0,n) scanf ("%d", p+i); while (m--) {scanf ("%d%d%d", &a,&b,&c); Add (A,B,C); Add (B,A,C); } scanf ("%d", &query); while (query--) {scanf ("%d%d%d", &a,&b,&c); int K=dijkstra (A,B,C); if (k==inf) printf ("impossible\n"); else printf ("%d\n", K); }} return 0;}
UVA-11367 full Tank? (Dijkstra)