uva1025
題意:有n個車站,起點車站和終點車站都有k輛列車分別在不同時刻出發,問從起點走的人在指定時刻到終點,最少要等多長時間。
分析:拿到題目,感覺很復雜,看了作者的分析,才明白怎么dp,看似不好dp,實際只要找到以時間為關鍵點,等待時間為dp對象就好做了,從t時刻終點開始,每次都有等1單位和乘向左或向右列車的方案。如果乘列車那么等待時間就不會變。
#include<iostream> #include<string.h> #include<sstream> #include<set> #include<algorithm> #include<vector> #include<map> #include<queue> #include<math.h> using namespace std; const int maxn=50+5; const int maxt = 200 + 5; const int INF = 10000000000;int t[maxn], has_train[maxt][maxn][2]; int dp[maxt][maxn]; int main() {int kase=0,n,T;while (cin >> n>>T&&n) {int M1, M2, d;for (int i = 1; i < n; i++)cin >> t[i];memset(has_train, 0, sizeof(has_train));cin >> M1;while (M1--) {int d;cin >> d;for (int j = 1; j < n; j++) {if (d <= T)has_train[d][j][0] = 1;d += t[j];}}cin >> M2;while (M2--) {int d;cin >> d;for (int j = n-1; j >0; j--) {if (d <= T)has_train[d][j+1][1] = 1;d += t[j];}}for (int j = 1; j < n; j++)dp[T][j] = 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;}return 0; }?
總結
- 上一篇: 动态规划三种方法
- 下一篇: uva437The Tower of B