MYF

UVa 1025 A Spy in the Metro

题目链接

UVa 1025

方法:DP

题目分析

题目大意

见紫书P267

解析

dp(i, j)记录在i时刻在第j个地铁站时所需要等待的最少时间,所以dp(0, 1)表示在零时刻所需等待的时间。将i从后往前递推,可以求出来dp(0, 1),即为解。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <iomanip>
#include <cstring>
#include <iostream>
#include <deque>
#include <algorithm>
#define Memset(a,val) memset(a,val,sizeof(a))
#define PI acos(-1)
#define rt(n) (i == n ? '\n' : ' ')
#define hi printf("Hi----------\n")
#define IN freopen("input.txt","r",stdin);
#define OUT freopen("output.txt","w",stdout);
#define debug(x) cout<<"Debug : ---"<<x<<"---"<<endl;
#pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long ll;
using namespace std;
const int maxn=100000+5;
const int mod=1000000007;
const int INF=0x3f3f3f3f;
const double eps=1e-8;
int main(){
int kase=1;
int n,T,t[220],f[220],e[220],dp[220][70],has_train[220][70][2];
while (~scanf("%d",&n)&&n) {
scanf("%d",&T);
for (int i=1; i<n; i++) {
scanf("%d",&t[i]);
}
int m1,m2;
scanf("%d",&m1);
for (int i=1; i<=m1; i++) {
scanf("%d",&f[i]);
}
scanf("%d",&m2);
for (int i=1; i<=m2; i++) {
scanf("%d",&e[i]);
}
Memset(has_train, 0);

for (int i=1; i<=m1; i++) {
int tt=f[i];
has_train[tt][1][0]=1;
for (int j=1; j<n; j++) {
tt+=t[j];
if (tt>T) break;
has_train[tt][j+1][0]=1;
}
}

for (int i=1; i<=m2; i++) {
int tt=e[i];
has_train[tt][n][1]=1;
for (int j=n; j>1; j--) {
tt+=t[j-1];
if (tt>T) break;
has_train[tt][j-1][1]=1;
}
}

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]);
}
}
}
cout<<"Case Number "<<kase++<<": ";
if (dp[0][1]>=INF)
cout<<"impossible\n";
else
cout<<dp[0][1]<<endl;
}
}