Tree Construction

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.
 
Input
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.
 
Output
Print the total length of edges in a line.
 
Sample Input
5
1 5
2 4
3 3
4 2
5 1
1
10000 0 
 
Sample Output
12


题目分析:一棵树只能向上和向右生长,求它能将所有给定二维坐标点连接起来的最短长度

                    刚开始题目没怎么看懂,纠结了一段时间,没想到怎么做,后来发现者可以用dp来

                   做,dp[i][j]表示从i到j所需要的最短距离,则dp[i][j]=dp[i][k]+dp[k+1][j]+abs(x[i]-x[k+1])+abs(y[k]-y[j])

                   显然,数据范围有点大枚举k的话时间复杂度为O(n^3),必定超时,于是需要优化,单调队列由于

                   绝对值的干扰不行,斜率优化貌似也行不通,于是想到了四边形不等式的优化,将决策k的范围

                   缩小,可以证明,该动态方程式具有单调性的,当a<b<c<d时,dp[a][c]+dp[b][d]<=dp[a][d]+dp[b][c];

                  因此决策k可缩小在k[i][j-1]和k[i+1][j]中,如此一来,效率大幅度提高,不会超时了。

代码:

#include<iostream>
using namespace std;
int dp[1005][1005],mm[1005][1005];
int main()
{
    int i,n,j;
    int x[1005],y[1005];
    while (~scanf("%d",&n))
    {
        for (i=1;i<=n;i++)
        {
            scanf("%d%d",&x[i],&y[i]);
            mm[i][i]=i;
        }
        memset(dp,0,sizeof(dp));
        for (int l=2;l<=n;l++)
        for (i=1;i<=n-l+1;i++)
        {
            dp[i][i+l-1]=999999;
            for (j=mm[i][i+l-2];j<=mm[i+1][i+l-1];j++)   //在可能最优决策中枚举
            {
                if (dp[i][i+l-1]>dp[i][j]+dp[j+1][i+l-1]+abs(x[i]-x[j+1])+abs(y[j]-y[i+l-1]))
                {
                    dp[i][i+l-1]=dp[i][j]+dp[j+1][i+l-1]+abs(x[i]-x[j+1])+abs(y[j]-y[i+l-1]);
                    mm[i][i+l-1]=j;  //记下每次的最优决策
                }
            }
        }
        printf("%d\n",dp[1][n]);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值