dp四边形优化 Hdu 3516 Tree Construction 题解

累加器传送门:

http://blog.csdn.net/NOIAu/article/details/71775000


题目传送门:

https://vjudge.net/problem/HDU-3516


题目:

Consider a two-dimensional space with a set of points (xi, yi) that satisfy xi < xj and yi > yj for all i < j. We want to have them all connected by a directed tree whose edges go toward either right (x positive) or upward (y positive). The figure below shows an example tree.
这里写图片描述

Write a program that finds a tree connecting all given points with the shortest total length of edges.


输入:

The input begins with a line that contains an integer n (1 <= n <= 1000), the number of points. Then n lines follow. The i-th line contains two integers xi and yi (0 <= xi, yi <= 10000), which give the coordinates of the i-th point.


输出:

Print the total length of edges in a line.


样例输入:

5
1 5
2 4
3 3
4 2
5 1
1
10000 0


样例输出:

12
0


题目大意:

二维平面上有n个,这些点满足
i < j时,xi < xj, yi > yj
只用朝x轴或y轴正方向的边连起来,形成一棵树,使得所有边的长度最小
其中 n <= 1000


很容易想到一个dp转移方程dp[i][j]=min{dp[i][k]+dp[k+1][j]+cost[i][k][k+1][j]}
这个cost[i][k][k+1][j]没必要预处理出来
模拟一下可以得到
它的值等于p[k].y-p[j].y+p[k+1].x-p[i].x
所以四边形优化就可以了,这篇博文有四边形优化详细讲解
http://blog.csdn.net/NOIAu/article/details/72514812


代码如下

#include<cstdio>
#include<cstring>
#include<iostream>
#define MAXN 1000+10
using namespace std;

int n;
int s[MAXN][MAXN],dp[MAXN][MAXN];

struct P{
    int x,y;
}p[MAXN];

bool init(){
    if(scanf("%d",&n)==EOF) return false;
    for(register int i=1;i<=n;i++) scanf("%d%d",&p[i].x,&p[i].y);
    for(register int i=1;i<=n;i++){
        dp[i][i]=0;
        s[i][i]=i;
    }
    return true;
}

void dpp(){
    for(register int i=n;i>=1;i--){
        for(register int j=i+1;j<=n;j++){
            int temp=0x7fffffff;
            int te;
            for(int k=s[i][j-1];k<=s[i+1][j];k++){
                if(k+1<=j){
                    if(temp>dp[i][k]+dp[k+1][j]+p[k].y-p[j].y+p[k+1].x-p[i].x){
                        temp=dp[i][k]+dp[k+1][j]+p[k].y-p[j].y+p[k+1].x-p[i].x;
                        te=k;
                    }
                }
            }
            dp[i][j]=temp;
            s[i][j]=te;
        }
    }
    cout<<dp[1][n]<<endl;
}
int main(){
    while(init()){
        dpp();
    }
    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值