dp uva1025

题目链接

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int INF = 1<<30;
 5 const int maxn = 50+5;
 6 const int maxt = 200+5;
 7 int N,T,a[maxn],t[maxn],M1,d,M2,e,dp[maxt][maxn],kase;
 8 bool has_train[maxt][maxn][2];
 9 
10 
11 void solve(){
12     for(int i=1; i<=N-1; i++) dp[T][i] = INF;
13     dp[T][N] = 0;
14 
15     for(int i=T-1; i>=0; i--){
16         for(int j=1; j<=N; j++){
17             dp[i][j] = dp[i+1][j]+1;
18             if(j<N && has_train[i][j][0] && i+t[j]<=T)
19                 dp[i][j] = min(dp[i][j],dp[i+t[j]][j+1]);
20             if(j>1 && has_train[i][j][1] && i+t[j-1]<=T)
21                 dp[i][j] = min(dp[i][j],dp[i+t[j-1]][j-1]);
22         }
23     }
24 
25 
26     cout << "Case Number " << ++kase << ": ";
27     if(dp[0][1] >= INF) cout << "impossible
";
28     else cout << dp[0][1] << endl;
29 }
30 
31 int main(){
32 
33     while(cin>>N && N){
34         memset(has_train,0,sizeof(has_train));
35         cin >> T;
36         for(int i=1; i<=N-1; i++)
37             cin >> t[i];
38         cin >> M1;
39         for(int i=0; i<M1; i++){
40             cin >> d;
41             for(int j=1; j<=N-1; j++){
42                 if(d <= T)
43                     has_train[d][j][0] = 1;
44                 d += t[j];
45 
46             }
47         }
48 
49         cin >> M2;
50         for(int i=0; i<M2; i++){
51             cin >> e;
52             for(int j=N-1; j>=1; j--){
53                 if(e <= T)
54                     has_train[e][j+1][1] = 1;
55                 e += t[j];
56             }
57         }
58 
59 
60         solve();
61     }
62 
63 }
原文地址:https://www.cnblogs.com/yxg123123/p/6827746.html