1. 程式人生 > >UVA1025-A Spy in the Metro(動態規劃)

UVA1025-A Spy in the Metro(動態規劃)

read min 圖片 ret 站點 pos ssi height names

Problem UVA1025-A Spy in the Metro

Accept: 713 Submit: 6160
Time Limit: 3000 mSec

技術分享圖片 Problem Description

技術分享圖片

Input

技術分享圖片

技術分享圖片 Output

For each test case, print a line containing the case number (starting with 1) and an integer representing the total waiting time in the stations for a best schedule, or the word ‘impossible’ in case Maria is unable to make the appointment. Use the format of the sample output.

技術分享圖片 Sample Input

4
55
5 10 15
4
0 5 10 20
4
0 5 10 15
4
18
1 2 3
5
0 3 6 10 12
6
0 3 5 7 12 15
2
30
20
1
20
7
1 3 5 7 11 13 17
0

技術分享圖片 Sample Output

Case Number 1: 5

Case Number 2: 0

Case Number 3: impossible

題解:很明顯的動態規劃,dp[i][j]表示i時刻在j站點還需要的最短等待時間,總共就三種選擇,狀態轉移方程很簡單,邊界一直是我寫動態規劃題比較頭疼的地方,不過這個題還比較簡單,t時刻在n站點自然是0,在其他站點就是INF(為了不會從這些狀態轉移過去)。

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 const int maxt = 200 + 10, maxn = 50 + 5;
6 const int INF = 0x3f3f3f3f; 7 8 int read() { 9 int q = 0; char ch = ; 10 while (ch<0 || ch>9) ch = getchar(); 11 while (0 <= ch && ch <= 9) { 12 q = q * 10 + ch - 0; 13 ch = getchar(); 14 } 15 return q; 16 } 17 18 int n, t, m1, m2; 19 int ti[maxn]; 20 int dp[maxt][maxn]; 21 bool have_train[maxt][maxn][2]; 22 23 void init() { 24 memset(have_train, false, sizeof(have_train)); 25 for (int i = 1; i <= n - 1; i++) { 26 dp[t][i] = INF; 27 } 28 dp[t][n] = 0; 29 } 30 31 int T = 1; 32 33 int main() 34 { 35 //freopen("input.txt", "r", stdin); 36 while (scanf("%d", &n) && n) { 37 t = read(); 38 init(); 39 for (int i = 1; i < n; i++) { 40 ti[i] = read(); 41 } 42 ti[n] = ti[0] = INF; 43 m1 = read(); 44 int d; 45 for (int i = 0; i < m1; i++) { 46 d = read(); 47 int cnt = 1; 48 for (int j = 1; j <= n; j++) { 49 have_train[d][cnt][0] = true; 50 //printf("d:%d cnt:%d\n", d, cnt); 51 cnt++; 52 d += ti[j]; 53 } 54 } 55 //printf("\n"); 56 57 m2 = read(); 58 for (int i = 0; i < m2; i++) { 59 d = read(); 60 int cnt = n; 61 for (int j = n; j >= 1; j--) { 62 have_train[d][cnt][1] = true; 63 //printf("d:%d cnt:%d\n", d, cnt); 64 cnt--; 65 d += ti[j - 1]; 66 } 67 } 68 69 for (int i = t - 1; i >= 0; i--) { 70 for (int j = 1; j <= n; j++) { 71 dp[i][j] = dp[i + 1][j] + 1; 72 if (i + ti[j] <= t && have_train[i][j][0]) { 73 dp[i][j] = min(dp[i][j], dp[i + ti[j]][j + 1]); 74 } 75 76 if (i + ti[j - 1] <= t && have_train[i][j][1]) { 77 dp[i][j] = min(dp[i][j], dp[i + ti[j - 1]][j - 1]); 78 } 79 } 80 } 81 82 printf("Case Number %d: ", T++); 83 if (dp[0][1] >= INF) { 84 printf("impossible\n"); 85 } 86 else { 87 printf("%d\n", dp[0][1]); 88 } 89 } 90 return 0; 91 }

UVA1025-A Spy in the Metro(動態規劃)