题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3516
题意:给定一些点(xi,yi)(xj,yj)满足:i<j,xi<xj,yi>yj。用下面的连起来,使得所有边的长度最小?
思路:设f[i][j]表示[i,j]区间的点连起来的最小代价,则f[i][j]=min(f[i][k]+f[k+1][j]+cost(i,j)),显然对于一个k,cost(i,j)=a[k].y-a[j].y+a[k+1].x-a[i].x。看上去跟四边形不等式有些关系,首先需要证明下面的两个:(a<b<c<d)
(1)cost(a,c)+cost(b,d)<=cost(b,c)+cost(a,d)
(2)cost(b,c)<=cost(a,d)
不好证明,有这个结论:w为凸当且仅当:cost(i,j)+cost(i+1,j+1)<=cost(i+1,j)+cost(i,j+1)。这个式子的证明是:首先固定j,计算cost(i,j+1)-cost(i,j)=a[i].y-a[i+1].y<0递减;同理固定i也是递减的,因此cost(i,j)是凸的。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <map>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)<(y)?(x):(y))
#define abs(x) ((x)>=0?(x):-(x))
#define i64 long long
#define u32 unsigned int
#define u64 unsigned long long
#define clr(x,y) memset(x,y,sizeof(x))
#define CLR(x) x.clear()
#define ph(x) push(x)
#define pb(x) push_back(x)
#define Len(x) x.length()
#define SZ(x) x.size()
#define PI acos(-1.0)
#define sqr(x) ((x)*(x))
#define MP(x,y) make_pair(x,y)
#define EPS 1e-9
#define FOR0(i,x) for(i=0;i<x;i++)
#define FOR1(i,x) for(i=1;i<=x;i++)
#define FOR(i,a,b) for(i=a;i<=b;i++)
#define FORL0(i,a) for(i=a;i>=0;i--)
#define FORL1(i,a) for(i=a;i>=1;i--)
#define FORL(i,a,b)for(i=a;i>=b;i--)
#define rush(n) for(scanf("%d",&C);C--;)
#define Rush(n) while(scanf("%d",&n)!=-1)
using namespace std;
void RD(int &x){scanf("%d",&x);}
void RD(u32 &x){scanf("%u",&x);}
void RD(double &x){scanf("%lf",&x);}
void RD(int &x,int &y){scanf("%d%d",&x,&y);}
void RD(u32 &x,u32 &y){scanf("%u%u",&x,&y);}
void RD(double &x,double &y){scanf("%lf%lf",&x,&y);}
void RD(int &x,int &y,int &z){scanf("%d%d%d",&x,&y,&z);}
void RD(int &x,int &y,int &z,int &t){scanf("%d%d%d%d",&x,&y,&z,&t);}
void RD(u32 &x,u32 &y,u32 &z){scanf("%u%u%u",&x,&y,&z);}
void RD(double &x,double &y,double &z){scanf("%lf%lf%lf",&x,&y,&z);}
void RD(char &x){x=getchar();}
void RD(char *s){scanf("%s",s);}
void RD(string &s){cin>>s;}
void PR(int x) {printf("%d\n",x);}
void PR(int x,int y) {printf("%d %d\n",x,y);}
void PR(int x,int y,int z) {printf("%d %d %d\n",x,y,z);}
void PR(i64 x) {printf("%lld\n",x);}
void PR(u32 x) {printf("%u\n",x);}
void PR(double x) {printf("%.5lf\n",x);}
void PR(char x) {printf("%c\n",x);}
void PR(char *x) {printf("%s\n",x);}
void PR(string x) {cout<<x<<endl;}
const int INF=1000000000;
const int N=1005;
struct point
{
int x,y;
void get()
{
RD(x,y);
}
};
point a[N];
int n,s[N][N],f[N][N];
int cost(int i,int k,int j)
{
return abs(a[k].y-a[j].y)+abs(a[k+1].x-a[i].x);
}
int main()
{
Rush(n)
{
int i,j,k,L,temp;
FOR1(i,n) a[i].get(),s[i][i]=i;
clr(f,0);
for(L=2;L<=n;L++) for(i=1;i+L-1<=n;i++)
{
j=i+L-1; f[i][j]=INF;
FOR(k,s[i][j-1],s[i+1][j])
{
temp=f[i][k]+f[k+1][j]+cost(i,k,j);
if(temp<f[i][j]) f[i][j]=temp,s[i][j]=k;
}
}
PR(f[1][n]);
}
return 0;
}