Tree Construction
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 689 Accepted Submission(s): 369
Problem Description
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.
![](https://i-blog.csdnimg.cn/blog_migrate/250971ecb3527f9d8319f947184c7f1f.jpeg)
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
Source
和取石子那一题很像,我们可以看出,dp[i][j]=min(dp[i][k]+dp[k=1][j]+cos[i,j])),可以用四边形优化,cos[i,j]=prime[k].y=prime].y+prime[k+1].x-prime[i].x,这题还是有很多地主要注意的!如,那个kk必须用等号,还要取绝对值!
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define MAXN 1005
#define inf 1000000000
struct node{
int x,y;
};
node prime[MAXN];
int dp[MAXN][MAXN],kk[MAXN][MAXN];
int fmin(int a,int b)
{
if(a<b)
return a;
return b;
}
int fabs(int a)
{
if(a<0)
return -a;
return a;
}
int fcost(int i,int j,int k)
{
return fabs(prime[k].y-prime[j].y)+fabs(prime[k+1].x-prime[i].x);//一定要加绝对值
}
int main()
{
int n,i,len,j,k;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
{
scanf("%d%d",&prime[i].x,&prime[i].y);
}
for(i=1;i<=n;i++)
{
kk[i][i]=i;
dp[i][i]=0;
}
for(len=2;len<=n;len++)
{
for(i=1;i<=n-len+1;i++)
{
j=i+len-1;
dp[i][j]=inf;
for(k=kk[i][j-1];k<=kk[i+1][j];k++)
{
int temp=dp[i][k]+dp[k+1][j]+fcost(i,j,k);
if(temp<dp[i][j])
{
dp[i][j]=temp;
kk[i][j]=k;
}
}
}
}
printf("%d\n",dp[1][n]);
}
return 0;
}