POJ3666 Making the Grade

题意

Language:
Making the Grade
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 11192 Accepted: 5201

Description

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

Source

分析

以《进阶指南》上的分析为准,结论是B中的数都在A中出现过。

\(F[i,j]\)表示完成前\(i\)个数的构造,其中\(B_i=j\)时,\(S\)的最小值。
\[ F[i,j]=\min_{0\le k\le j}\{F[i-1,k]+|A_i-j|\} \]
决策集合只增多不减少,转移可以维护成\(O(1)\)。时间复杂度\(O(N^2)\)

代码

虽然说要做两遍,但是做一遍算出来也是对的?

#include<iostream>
#include<algorithm>
#include<cstring>
#define rg register
#define il inline
#define co const
template<class T>il T read(){
    rg T data=0,w=1;rg char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-') w=-1;ch=getchar();}
    while(isdigit(ch)) data=data*10+ch-'0',ch=getchar();
    return data*w;
}
template<class T>il T read(rg T&x) {return x=read<T>();}
typedef long long ll;

co int N=2001;
int n,a[N],b[N],f[N][N];
int main(){
//  freopen(".in","r",stdin),freopen(".out","w",stdout);
    read(n);
    for(int i=1;i<=n;++i) b[i]=read(a[i]);
    std::sort(b+1,b+n+1);
    int m=std::unique(b+1,b+n+1)-b-1;
    memset(f,0x3f,sizeof f);
    f[0][0]=0;
    for(int i=1;i<=n;++i){
        int temp=f[i-1][0];
        for(int j=1;j<=m;++j){
            temp=std::min(temp,f[i-1][j]);
            f[i][j]=temp+abs(a[i]-b[j]);
        }
    }
    int ans=1<<30;
    for(int i=1;i<=m;++i) ans=std::min(ans,f[n][i]);
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/autoint/p/10664416.html
今日推荐