POJ 1611 Help Jimmy(DP,坑)

来源:互联网 发布:全网通是什么网络制式 编辑:程序博客网 时间:2024/05/16 16:54

中文题面....这个题目挺难得...我写了两小时才AC的...

思路是这样的,如果我想知道他到地面最短的时间,只需要知道老鼠落在第一个平台上时,min(ltime,rtime),ltime是往左走到地面的最短时间,rtime往右走到底地面的最短时间,要想知道ltime和rtime,需要求得第一个平台往左走下去是落在第i个平台,然后再次求得第i个平台的min(ltime,rtime),加上下落时间...这样问题就分解为一个个子问题...符合了动态规划...然后既然思考就是这样,那么就记忆化搜索的方式写吧.....

题目中需要注意几个问题,注释里有写

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<algorithm>using namespace std;#define inf 1<<30struct node{    int x1,x2,h;} s[1234];int cmp(node a,node b){    return a.h>b.h;}int n,dp[1234][2],maxh;int dfs(int t,int zy){    if(dp[t][zy])        return dp[t][zy];    int x,i;    if(zy==0) x=s[t].x1;    else x=s[t].x2;    for(i=t+1; i<=n; i++)        if(s[i].x1<=x&&s[i].x2>=x&&s[t].h-s[i].h<=maxh)            break;    if(i>n)    {        if(s[t].h>maxh)            dp[t][zy]=inf;        else            dp[t][zy]=s[t].h;        return dp[t][zy];    }    int ltime=s[t].h-s[i].h+abs(x-s[i].x1);    int rtime=s[t].h-s[i].h+abs(x-s[i].x2);    ltime+=dfs(i,0);    rtime+=dfs(i,1);    return dp[t][zy]=min(ltime,rtime);}int main(){    int T;    cin>>T;    while(T--)    {        int x,y,i;        cin>>n>>x>>y>>maxh;        for(i=1; i<=n; i++)            scanf("%d %d %d",&s[i].x1,&s[i].x2,&s[i].h);        sort(s+1,s+n+1,cmp);//题目给出的高度是无序的,所以先按照高度排序        memset(dp,0,sizeof(dp));        for(i=1; i<=n; i++)        {            if(s[i].x1<=x&&s[i].x2>=x&&y-s[i].h<=maxh)//如果你在x点下落,下面平台的范围是(x,y),那么你还是会落在这个平台上                break;        }        int ans;        if(i>n)//有可能直接落在地面            ans=y;        else        {            ans=y-s[i].h;            int l=abs(x-s[i].x1)+dfs(i,0);            int r=abs(x-s[i].x2)+dfs(i,1);            ans+=min(l,r);        }        cout<<ans<<endl;    }    return 0;}
PS:今天情人节,单身狗受到了极大的嘲讽....

0 0
原创粉丝点击