A straight dirt road connects two fields on FJ's farm, but it changes elevation more than FJ would like. His cows do not mind climbing up or down a single slope, but they are not fond of an alternating succession of hills and valleys. FJ would like to add and remove dirt from the road so that it becomes one monotonic slope (either sloping up or down).
You are given N integers A1, ... , AN (1 ≤ N ≤ 2,000) describing the elevation (0 ≤ Ai ≤ 1,000,000,000) at each of N equally-spaced positions along the road, starting at the first field and ending at the other. FJ would like to adjust these elevations to a new sequence B1, . ... , BN that is either nonincreasing or nondecreasing. Since it costs the same amount of money to add or remove dirt at any position along the road, the total cost of modifying the road is
| A 1 - B 1| + | A 2 - B 2| + ... + | AN - BN |
Please compute the minimum cost of grading his road so it becomes a continuous slope. FJ happily informs you that signed 32-bit integers can certainly be used to compute the answer.
Input
* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer elevation: Ai
Output
* Line 1: A single integer that is the minimum cost for FJ to grade his dirt road so it becomes nonincreasing or nondecreasing in elevation.
Sample Input
7 1 3 2 4 5 3 9
Sample Output
3
题意:给定一个序列an,要求花费最小的代价将它变成非严格单调递增序列或非严格单调递减序列bn.
思路:这个dp比较难想,但有一点我们需要先明白,那就是修改后的元素一定都是原序列an里的,也就是说,要实现最小的花费,我们只能让不其满足非严格单调:
例如 a: 1 3 2 4
我们最好的修改方式就是,将2变成3-----> 1 3 3 4,这样是最优的解。
所以我们定义: dp[i][j]为前i个数,且第i个数位原来第j 大的数,花费的最小代价:
状态转移:dp[i][j]=min(dp[i-1][k]+abs(a[i]-b[k])) k>=1&&k<j;
下面给出代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <sstream>
#include <stack>
typedef long long ll;
const int INF=100000;
const int maxn=1e5+10;
using namespace std;
int n;
ll dp[2005][2005];
ll a[maxn],b[maxn];
int main(int argc, char const *argv[])
{
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
b[i]=a[i];
}
sort(b+1,b+n+1);
ll t;
for(int i=1;i<=n;i++)
{
dp[1][i]=a[1]-b[i];
if(dp[1][i]<0)
{
dp[1][i]=-dp[1][i];
}
}
for(int i=2;i<=n;i++)
{
ll k=dp[i-1][1];
for(int j=1;j<=n;j++)
{
k=min(dp[i-1][j],k);
t=a[i]-b[j];
if(t<0) t=-t;
dp[i][j]=k+t;
}
}
ll ans=dp[n][n];
for(int i=1;i<n;i++)
{
ans=min(ans,dp[n][i]);
}
cout<<ans<<endl;
}
return 0;
}