列表

详情


NC51153. Making the Grade

描述

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 describing the elevation 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

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.

示例1

输入:

7
1
3
2
4
5
3
9

输出:

3

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 22ms, 内存消耗: 31780K, 提交时间: 2020-07-20 10:45:20

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
int a[2005],b[2005];
ll dp[2005][2005];
	
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	cin >> n;
	for(int i=1;i<=n;i++){
		cin >> a[i];
		b[i]=a[i];
	}
	sort(b+1,b+n+1);
	for(int i=1;i<=n;i++){
		ll minn=dp[i-1][1];
		for(int j=1;j<=n;j++){
			minn=min(minn,dp[i-1][j]);
			dp[i][j]=abs(a[i]-b[j])+minn;
		}
	}
	ll ans=dp[n][1];
	for(int i=1;i<=n;i++)
		ans=min(ans,dp[n][i]);
	printf("%lld\n",ans);
	
	return 0;
}

C++(clang++11) 解法, 执行用时: 3ms, 内存消耗: 504K, 提交时间: 2021-02-04 22:53:46

#include<bits/stdc++.h>
int n,a;
long long ans;
std::priority_queue<int>q;
int main(){
    scanf("%d",&n);
    while(n--){
        scanf("%d",&a);
        q.push(a);
        if(a<q.top()){
            ans+=q.top()-a;
            q.pop();
            q.push(a);
        }
    }
    printf("%lld",ans);
}

上一题