累加器传送门:
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;
}