9-1 http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem= 3466
The book is recursive, I wrote a memory search DP
There are 3 kinds of decisions, the left car, the right car, stay in place,
1#include <cstdio>2#include <cstring>3#include <algorithm>4 #defineMT (A, b) memset (A,b,sizeof (a))5 using namespacestd;6 Const intinf=0x3f3f3f3f;7 Const intm= -;8 intW[m];9 BOOLleft[m][ the];Ten BOOLright[m][ the]; One intdp[m][ the]; A BOOLvis[m][ the]; - intn,t; - intDfsintNintt) { the if(Vis[n][t])returnDp[n][t]; -vis[n][t]=true; - int& ans=Dp[n][t]; -ans=inf; + if(n>1&&t>=w[n-1]){ - for(intI=0; i<=t-w[n-1];i++){ + if(left[n-1][i]) { AAns=min (Ans,dfs (n1, i) +t-i-w[n-1]); at } - } - } - if(n<n&&t>=W[n]) { - for(intI=0; i<=t-w[n];i++){ - if(right[n+1][i]) { inAns=min (Ans,dfs (n+1, i) +t-i-w[n]); - } to } + } - for(intI=0; i<=t;i++){ theAns=min (Ans,dfs (n,i) +t-i); * } $ returnans;Panax Notoginseng } - intMain () { the intm,x,cas=1; + while(~SCANF ("%d",&N), N) { Ascanf"%d",&T); the for(intI=1; i<n;i++){ +scanf"%d",&w[i]); - } $MT (left,0); $MT (right,0); -scanf"%d",&m); - while(m--){ thescanf"%d",&x); - for(intI=1; i<=n;i++){Wuyi if(x>t) Break; theleft[i][x]=true; -x+=W[i]; Wu } - } Aboutscanf"%d",&m); $ while(m--){ -scanf"%d",&x); - for(inti=n;i>=1; i--){ - if(x>t) Break; Aright[i][x]=true; +x+=w[i-1]; the } - } $MT (Vis,0); thevis[1][0]=true; thedp[1][0]=0; the intans=DFS (n,t); theprintf"Case Number %d:", cas++); - if(Ans==inf) puts ("Impossible"); in Elseprintf"%d\n", ans); the } the return 0; About}
View Code
End
Introduction to the algorithm Classic second Edition purple book the 9th Chapter dynamic Programming Preliminary