poj1661

本文通过一个具体的例子详细介绍了如何使用动态规划算法解决特定类型的问题。包括输入处理、状态定义、状态转移方程等核心内容。

dp

ContractedBlock.gifExpandedBlockStart.gifView Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#include
<algorithm>
using namespace std;

#define maxn 1005

struct Plat
{
int l, r, h, lt, rt;
} plat[maxn];

int n, m, cx, cy;

bool operator <(const Plat &a, const Plat &b)
{
return a.h > b.h;
}

void input()
{
scanf(
"%d%d%d%d", &n, &cx, &cy, &m);
plat[
0].l = plat[0].r = cx;
plat[
0].h = cy;
for (int i = 1; i <= n; i++)
{
scanf(
"%d%d%d", &plat[i].l, &plat[i].r, &plat[i].h);
if (plat[i].l > plat[i].r)
swap(plat[i].l, plat[i].r);
}
}

void work()
{
int j;
int ans = 0x3f3f3f3f;
for (int i = 0; i <= n; i++)
plat[i].lt
= plat[i].rt = 0x3f3f3f3f;
plat[
0].lt = plat[0].rt = 0;
for (int i = 0; i <= n; i++)
{
for (j = i + 1; j <= n; j++)
{
if (plat[i].h - plat[j].h > m)
break;
if (plat[i].h == plat[j].h)
continue;
if (plat[i].l <= plat[j].r && plat[i].l >= plat[j].l)
{
plat[j].lt
= min(plat[i].h - plat[j].h + plat[i].lt + abs(
plat[i].l
- plat[j].l), plat[j].lt);
plat[j].rt
= min(plat[i].h - plat[j].h + plat[i].lt + abs(
plat[i].l
- plat[j].r), plat[j].rt);
break;
}
}
if (j > n && plat[i].h <= m)
ans
= min(ans, plat[i].lt + plat[i].h);
for (j = i + 1; j <= n; j++)
{
if (plat[i].h - plat[j].h > m)
break;
if (plat[i].h == plat[j].h)
continue;
if (plat[i].r <= plat[j].r && plat[i].r >= plat[j].l)
{
plat[j].lt
= min(plat[i].h - plat[j].h + plat[i].rt + abs(
plat[i].r
- plat[j].l), plat[j].lt);
plat[j].rt
= min(plat[i].h - plat[j].h + plat[i].rt + abs(
plat[i].r
- plat[j].r), plat[j].rt);
break;
}
}
if (j > n && plat[i].h <= m)
ans
= min(ans, plat[i].rt + plat[i].h);
}
printf(
"%d\n", ans);
}

int main()
{
//freopen("t.txt", "r", stdin);
int t;
scanf(
"%d", &t);
while (t--)
{
input();
sort(plat, plat
+ n + 1);
work();
}
return 0;
}

转载于:https://www.cnblogs.com/rainydays/archive/2011/06/16/2082592.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值