标签:
9-1 http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3466
书上是递推的,我写了个记忆化搜索dp
有3种决策,左边的车,右边的车,原地不动,
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #define mt(a,b) memset(a,b,sizeof(a)) 5 using namespace std; 6 const int inf=0x3f3f3f3f; 7 const int M=64; 8 int w[M]; 9 bool left[M][256]; 10 bool right[M][256]; 11 int dp[M][256]; 12 bool vis[M][256]; 13 int N,T; 14 int dfs(int n,int t){ 15 if(vis[n][t]) return dp[n][t]; 16 vis[n][t]=true; 17 int& ans=dp[n][t]; 18 ans=inf; 19 if(n>1&&t>=w[n-1]){ 20 for(int i=0;i<=t-w[n-1];i++){ 21 if(left[n-1][i]){ 22 ans=min(ans,dfs(n-1,i)+t-i-w[n-1]); 23 } 24 } 25 } 26 if(n<N&&t>=w[n]){ 27 for(int i=0;i<=t-w[n];i++){ 28 if(right[n+1][i]){ 29 ans=min(ans,dfs(n+1,i)+t-i-w[n]); 30 } 31 } 32 } 33 for(int i=0;i<=t;i++){ 34 ans=min(ans,dfs(n,i)+t-i); 35 } 36 return ans; 37 } 38 int main(){ 39 int m,x,cas=1; 40 while(~scanf("%d",&N),N){ 41 scanf("%d",&T); 42 for(int i=1;i<N;i++){ 43 scanf("%d",&w[i]); 44 } 45 mt(left,0); 46 mt(right,0); 47 scanf("%d",&m); 48 while(m--){ 49 scanf("%d",&x); 50 for(int i=1;i<=N;i++){ 51 if(x>T) break; 52 left[i][x]=true; 53 x+=w[i]; 54 } 55 } 56 scanf("%d",&m); 57 while(m--){ 58 scanf("%d",&x); 59 for(int i=N;i>=1;i--){ 60 if(x>T) break; 61 right[i][x]=true; 62 x+=w[i-1]; 63 } 64 } 65 mt(vis,0); 66 vis[1][0]=true; 67 dp[1][0]=0; 68 int ans=dfs(N,T); 69 printf("Case Number %d: ",cas++); 70 if(ans==inf) puts("impossible"); 71 else printf("%d\n",ans); 72 } 73 return 0; 74 }
end
标签:
原文地址:http://www.cnblogs.com/gaolzzxin/p/4495352.html