经典dp(状态之间相互l利用)

注意这里的状态只能定义为d[ i ][ j ]表示i位置还没被确定采取什么高度,还可选的高度在j -n之间、

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
#define rep(i,n) for(int (i)=0;(i)<(n);i++)
#define Rep(i,n) for(int (i)=1;(i)<=(n);i++)
const int maxn = 2110;
int n,a[maxn],b[maxn];
LL  d[maxn][maxn];
void init(){
  Rep(i,n+1) Rep(j,n+1)
    d[i][j] = -1;
}
LL dp(int i,int j){
  if(d[i][j]!=-1) return d[i][j];
  if(i == n+1){
     return d[i][j] = 0;
  }
  d[i][j] = dp(i+1,j)+abs(a[i]-b[j]);
  if(j<n) d[i][j]=min(d[i][j],dp(i,j+1));
  return d[i][j];
}
LL dp2(int i,int j){
  if(d[i][j]!=-1) return d[i][j];
  if(i == n+1){
     return d[i][j] = 0;
  }
  d[i][j] = dp2(i+1,j)+abs(a[i]-b[j]);
  if(j>1) d[i][j]=min(d[i][j],dp2(i,j-1));
  return d[i][j];
}
int main()
{
   while(scanf("%d",&n)==1){
     for(int i=1;i<=n;i++){
       scanf("%d",&a[i]);
       b[i]= a[i];
     }
     sort(b+1,b+1+n);
     init();
     LL ans = dp(1,1);
     init();
     ans = min(ans,dp(1,n));
     cout<<ans<<endl;
   }
   return 0;
}


你可能感兴趣的:(Algorithm,poj)