Uva1025 A Spy in the Metro (dp)

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3466

题意:在一个线性的地铁有1-n个站,有人要从1出发在T时刻去站点n会见一个人。在的铁上有m1辆地铁从1到n走,有m2个地铁从n到1走。他可以在地铁列车上换乘。求出他在等待的最短时间。如果没有则输出impossi。

解法:我们用d[i][j]表示时刻i,你在车站j最少还需要等待多长时间。边界条件为d[T][n]=0。对于当前状态,共有三种决策,1.原地等待,2.搭上向左开的车,3.搭上向右开的车


AC:

#include <algorithm>
#include <string>
#include <iostream>
#include <string.h>
#include<stdio.h>
#include<cmath>
#include<vector>
using namespace std;
#define ll  long long int
#define debug
const int maxn=500;
const int inf=1000000;
int t[maxn],dp[maxn][maxn],T;
int d,m1,m2,n;
bool have_train[maxn][maxn][2];
int main()
{
   //freopen("in.txt","r",stdin);
   int cnt=0;
   while(scanf("%d",&n)!=EOF&&n)
   {
       scanf("%d",&T);
       memset(have_train,0,sizeof(have_train));
        for(int i=1;i<n;i++)
        {
            scanf("%d",&t[i]);
        }
        scanf("%d",&m1);
        for(int i=1;i<=m1;i++)
        {
            scanf("%d",&d);
            if(d>T) continue;
            have_train[d][1][0]=1;
            for(int j=1;j<n;j++)
            {
                if(d+t[j]>T) break;
                else
                {
                    d=d+t[j]; have_train[d][j+1][0]=1;
                }
            }
        }
        scanf("%d",&m2);
        for(int i=1;i<=m2;i++)
        {
            scanf("%d",&d);
            if(d>T) continue;
            have_train[d][n][1]=1;
            for(int j=n-1;j>=1;--j)
            {
                if(d+t[j]>T) break;
                else
                {
                    d=d+t[j];
                    have_train[d][j][1]=1;
                }
            }
        }
        for(int i=0;i<=n-1;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&&have_train[i][j][0] &&i+t[j]<=T)
                {
                    dp[i][j]=min(dp[i][j],dp[i+t[j]][j+1]);
                }
                if(j>1&&have_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: ",++cnt);
        if(dp[0][1]>=inf) printf("impossible\n");
        else printf("%d\n",dp[0][1]);
   }

}

你可能感兴趣的:(Uva1025 A Spy in the Metro (dp))