以dp[i][j] 表示 第i分到第j站最长的等待时间,INF表示在第i分的时候到不到j站。
有3个决策。
1:当前等待一分钟。
2: 乘坐往右的车(如果有)
3: 乘坐往左的车(如果有)
主要过程代码与紫书类似,不过我是从i=1开始枚举的。
主要就是has_train的处理。
车的出发时间加上站与站之间的时间就可以算出第i分到第j站
void check_train(){
for(int i=1;i<=m1;i++){
int res = t1[i];
for(int j=0;j<n;j++){
res += t[j];
if(res <= T) has_train[res][j+1][0] = 1;
}
}
for(int i=1;i<=m2;i++){
int res = t2[i];
for(int j=n;j>0;j--){
res += t[j];
if(res <= T) has_train[res][j][1] = 1;
}
}
}
总代码
t[n] 是一定要初始化为0,这关系到我自己写的 check_train函数。
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#include<bits/stdc++.h>
#define int long long
using namespace std;
typedef pair<int,int> pii;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const double eps = 1e-4;
const int mod = 1e9+7;
const int N = 210;
int n,T,z=0;
int t[N],t1[N],t2[N];
int dp[N][N],m1,m2;
int has_train[N][N][2];
void init(){
for(int i=0;i<N;i++){
t[i] = 0;
for(int j=0;j<N;j++){
has_train[i][j][0] = has_train[i][j][1] = 0;
dp[i][j] = INF;
}
}
dp[0][1] = 0;
}
void read(){
for(int i=1;i<n;i++) cin>>t[i];
cin>>m1;
for(int i=1;i<=m1;i++) cin>>t1[i];
cin>>m2;
for(int i=1;i<=m2;i++) cin>>t2[i];
}
void check_train(){
for(int i=1;i<=m1;i++){
int res = t1[i];
for(int j=0;j<n;j++){
res += t[j];
if(res <= T) has_train[res][j+1][0] = 1;
}
}
for(int i=1;i<=m2;i++){
int res = t2[i];
for(int j=n;j>0;j--){
res += t[j];
if(res <= T) has_train[res][j][1] = 1;
}
}
}
void slove(){
for(int i=1;i<=T;i++){
for(int j=1;j<=n;j++){
dp[i][j] = dp[i-1][j] + 1;
if(j > 1 && has_train[i][j][0] && i-t[j-1] >= 0)//右
dp[i][j] = min(dp[i][j],dp[i-t[j-1]][j-1]);
if(j < n && has_train[i][j][1] && i-t[j] >= 0)//左
dp[i][j] = min(dp[i][j],dp[i-t[j]][j+1]);
}
}
}
signed main(){
// IOS;
#ifdef ddgo
freopen("C:/Users/asus/Desktop/ddgoin.txt","r",stdin);
#endif
while(cin>>n && n){
cin>>T;
init();
read();
check_train();
slove();
cout<<"Case Number "<<++z<<": ";
if(dp[T][n] >= INF) cout<<"impossible"<<endl;
else cout<<dp[T][n]<<endl;
}
return 0;
}