BZOJ 1592 DP
思路:f[i][j]表示前i个数 最后一个数是原数列的第j个的 最小值
//By SiriusRen
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,a[2222],cpy[2222],minn[2222],f[2222][2222],temp[2222],ans=0x7fffffff;
void work(){
memset(f,0x3f,sizeof(f));
memset(minn,0,sizeof(minn));
for(int i=1;i<=n;i++){
memset(temp,0x3f,sizeof(temp));
for(int j=1;j<=n;j++){
f[i][j]=min(minn[j]+abs(cpy[j]-a[i]),f[i][j]);
if(j==1)temp[j]=f[i][j];
else temp[j]=min(temp[j-1],f[i][j]);
}
for(int j=1;j<=n;j++)minn[j]=temp[j];
}
for(int i=1;i<=n;i++)ans=min(ans,f[n][i]);
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&a[i]),cpy[i]=a[i];
sort(cpy+1,cpy+1+n);
work(),reverse(a+1,a+1+n),work();
printf("%d\n",ans);
}