动态规划基础例题,要理解状态和状态转移方程。。。
#include <bits/stdc++.h>
using namespace std;
int kase = 0;
int n, T, t[80];
int M1, M2, st1[64], st2[64];
bool has_train[512][64][2];
int dp[512][80];
const int INF = 1<<8;
int main() {
//freopen("in.txt", "r", stdin);
while(cin >> n && n) {
memset(dp, 0, sizeof(dp));
memset(has_train, false, sizeof(has_train));
memset(st1, 0, sizeof(st1));
memset(st2, 0, sizeof(st2));
cin >> T;
for(int i = 1; i < n; ++i) cin >> t[i];
cin >> M1;
for(int i = 1; i <= M1; ++i) {
cin >> st1[i];
int time = st1[i];
for(int j = 1; j <= n; ++j) {
has_train[time][j][0] = true;
time += t[j];
if(time > 202) break;
}
}
cin >> M2;
for(int i = 1; i <= M2; ++i) {
cin >> st2[i];
int time = st2[i];
for(int j = n; j >= 1; --j) {
has_train[time][j][1] = true;
time += t[j-1];
if(time > 202) break;
}
}
for(int i = 1; i < n; ++i) dp[T][i] = INF;
dp[T][n] = 0;
for(int i = T-1; i >= 0; --i) {
for(int j = 1; j <= n; ++j) {
dp[i][j] = dp[i+1][j] + 1;
if(j < n && has_train[i][j][0] && i+t[j] <= T)
dp[i][j] = min(dp[i][j], dp[i+t[j]][j+1]);
if(j > 1 && has_train[i][j][1] && i+t[j-1] <= T)
dp[i][j] = min(dp[i][j], dp[i+t[j-1]][j-1]);
}
}
printf("Case Number %d: ", ++kase);
if(dp[0][1] >= INF) cout << "impossible" << endl;
else cout << dp[0][1] << endl;
}
return 0;
}