题目描述
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
|A1 – B1| + |A2 – B2| + … + |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.
输入输出格式
输入格式:
* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer elevation: Ai
输出格式:
* 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.
样例输入 :
7
1
3
2
4
5
3
9
样例输出:
3

题解
首先有一个比较显然的结论:b序列里的数全部都在a序列里出现过,我们可以这么理解:如果要使得花费尽可能的小,那么我们要使得修改后的序列和原序列差的尽可能小。 且此题单调递增和单调递减的情况花费完全相同
那么。。
贪心!
先说操作(以单调非降为例): 从左到右,把当前位置的数放进大根堆,然后比较这个数和堆顶的大小。
若比堆顶大,就不管
若比堆顶小,就把堆顶拿出来变成这个数,然后答案增加堆顶与这个数的差。
时间复杂度O(nlog n)。
悄悄咪咪贴个代码:
#include<iostream>
#include<queue>
using namespace std;
priority_queue<int >q;
int a[10005],ans;
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
for(int i=1;i<=n;i++)
{
q.push(a[i]);
ans+=q.top()-a[i];
q.pop();
q.push(a[i]);
}
cout<<ans;
}