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
0
题目分析:一棵树只能向上和向右生长,求它能将所有给定二维坐标点连接起来的最短长度
刚开始题目没怎么看懂,纠结了一段时间,没想到怎么做,后来发现者可以用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]);
}
}