UVA 1025A Spy in the Metro (简单DP)

来源:互联网 发布:vm虚拟机网络连接 编辑:程序博客网 时间:2024/05/28 11:29
#include <bits/stdc++.h>#define INF 0x3f3f3f3f#define eps 1e-6typedef long long LL;const double pi = acos(-1.0);const long long mod = 1e9 + 7;using namespace std;const int MAXN = 55;const int MAXT = 205;int dp[MAXT][MAXN];//dp[i][j]表示在时刻i,并且你在车站j,最少还需要等待多少时间才能到终点int has_train[MAXT][MAXN][2];//has_train[i][j][0]表示在时刻i,车站j是否有往右开的车//has_train[i][j][1]表示在时刻i,车站j是否有往左开的车int t[MAXN];//t[i]表示第i个车站开往第i+1个车站所需要花费的时间int d1[MAXN],d2[MAXN];//d1[i]表示往右开的第i辆车的出发时间,d2[i]表示往左开的第i辆车的出发时间int main(){    int T,N;    int cas = 1;    while(cin >> N && N)    {        memset(has_train,0,sizeof(has_train));        cin >> T;        for(int i = 1;i < N;i++)            cin >> t[i];        int M1,M2;        cin >> M1;        for(int i = 1;i <= M1;i++)            cin >> d1[i];        cin >> M2;        for(int i = 1;i <= M2;i++)            cin >> d2[i];        for(int i = 1;i <= M1;i++)        {            has_train[d1[i]][1][0] = 1;            int temp = d1[i];            for(int j = 1;j < N;j++)            {                temp += t[j];                if(temp <= T)                    has_train[temp][j + 1][0] = 1;                else                    break;            }        }        for(int i = 1;i <= M2;i++)        {            has_train[d2[i]][N][1] = 1;            int temp = d2[i];            for(int j = N - 1;j > 0;j--)            {                temp += t[j];                if(temp <= T)                    has_train[temp][j][1] = 1;                else                    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: ",cas++);        if(dp[0][1] >= INF)            puts("impossible");        else            printf("%d\n",dp[0][1]);    }    return 0;}
0 0
原创粉丝点击