poj - 2661 Help Jimmy 动态规划

题目链接:http://poj.org/problem?id=1661

题意:中文题

思路:dp,但是有很多细节需要考虑,因此WA了很多发,具体看代码注释。

 

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

struct ban
{
	int l, r, h;
	bool operator < (const ban A) const
	{
		return h > A.h;
	}
}a[1010];

int dp[1010][2]; //dp[i][0]为到达第i块木板左端点的最短时间,dp[i][1]为到达第i块木板右端点的最短时间

inline int min(int a,int b) {return a < b ? a : b; }

int main()
{
	int T, n, x, y, MAX, ans;
	cin>>T;
	while(T--){
		ans = 0x3f3f3f3f;
		memset(dp, 0x3f, sizeof dp);
		cin>>n>>x>>y>>MAX;
		for(int i = 1; i <= n; ++i){
			cin>>a[i].l>>a[i].r>>a[i].h;
		}
		sort(a+1,a+n+1); //按高度进行排序
		int s = 0;
		for(int i = 1; i <= n; ++i){ //寻找jimmy落在哪一块木板上,从该块木板开始dp
			if(a[i].l <= x && x <= a[i].r){
				s = i;
				dp[i][0] = x - a[i].l + y - a[i].h;
				dp[i][1] = a[i].r - x + y - a[i].h;
				break;	
			}
		}
		if(!s){	//如果没有落在木板上,即为直接落在地上,初始高度即为答案
			cout<<y<<'\n';
			continue;
		}
		int L, R;
		for(int i = s; i <= n; ++i){
			L = R = 0; //从第i块木板的左右端点出发,只能到达下方的第一块木板
			for(int j = i + 1; j <= n; ++j){
				if(a[i].h - a[j].h > MAX)
					break;
				if(!L && a[j].l <= a[i].l && a[i].l <= a[j].r){
					dp[j][0] = min(dp[j][0], dp[i][0] + a[i].l - a[j].l + a[i].h - a[j].h);
					dp[j][1] = min(dp[j][1], dp[i][0] + a[j].r - a[i].l + a[i].h - a[j].h);
					L = 1;
				}
				if(!R && a[j].l <= a[i].r && a[i].r <= a[j].r){
					dp[j][0] = min(dp[j][0], dp[i][1] + a[i].r - a[j].l + a[i].h - a[j].h);
					dp[j][1] = min(dp[j][1], dp[i][1] + a[j].r - a[i].r + a[i].h - a[j].h);
					R = 1;
				}
			}
		}
		int flag = 0, flag1 = 0;//最后的答案即为所有可以直接到达地面的端点的花费时间最小值,注意高度的限制
		for(int i = s; i <= n; ++i){
			flag = flag1 = 0;
			for(int j = i + 1; j <= n; ++j){
				if(flag && flag1) break;
				if(a[j].l <= a[i].l && a[i].l <= a[j].r)
					flag = 1;
				if(a[j].l <= a[i].r && a[i].r <= a[j].r)
					flag1 = 1;
			}
			if(!flag && a[i].h <= MAX)
				ans = min(ans, dp[i][0] + a[i].h);
			if(!flag1 && a[i].h <= MAX)
				ans = min(ans, dp[i][1] + a[i].h);
		}
		cout<<ans<<'\n';
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值