首先,这道题的数据特别水,我们主要写验证他不严格升序的代码即可。
通过分析我们能够发现,影响前i个数所用的总消耗只收前i-1个数的总消耗与第i-1个数的高度相关,所以我们可以用二维数组dp[i][j]表示使得前i个数不严格递增,并且最大高度为j所用的花费。
再分析,在计算dp[i][j]的时候,第i个数字的大小一定是j,所以我们只需要在dp[i-1][0]到dp[i-1][j]中取最小的一个即可,选择哪个并不会对我们在数字i上的花销造成影响。
因为数据比较大,我们需要对他做简单的离散化处理。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <string>
#include <map>
#include <queue>
#include <vector>
#include <stack>
#define N 2200
#define ll long long
#define INF 0x7fffffff
using namespace std;
int n;
int heigh[N];
int sortheigh[N];
int dp[N][N];
int main(){
int i,j;
int mn = INF;
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&heigh[i]);
sortheigh[i] = heigh[i];
}
sort(sortheigh+1,sortheigh+1+n);
memset(dp,0x3f,sizeof(dp));
dp[0][0] = 0;
for(i=1;i<=n;i++){
mn = INF;
for(j=0;j<=n;j++){
mn = min(mn,dp[i-1][j]);
dp[i][j] = mn + abs(heigh[i] - sortheigh[j]);
}
}
int ans = INF;
for(i=1;i<=n;i++){
ans = min(ans,dp[n][i]);
}
printf("%d\n",ans);
return 0;
}