列表

详情


NC24960. 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 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.

示例1

输入:

7
1
3
2
4
5
3
9

输出:

3

说明:

By changing the first 3 to 2 and the second 3 to 5 for a total cost of |2-3|+|5-3| = 3 we get the nondecreasing sequence 1,2,2,4,5,5,9.

原站题解

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

C++14(g++5.4) 解法, 执行用时: 33ms, 内存消耗: 31904K, 提交时间: 2019-07-22 09:47:43

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;


ll a[2005],b[2005],dp[2005][2005],n;

int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
        b[i]=a[i];
    }
    sort(b+1,b+1+n);
    memset(dp,0,sizeof(dp));
    for(int i=1;i<=n;i++)
    {
        ll minn=1e9+1;
        for(int j=1;j<=n;j++)
        {
            minn=min(dp[i-1][j],minn);
            dp[i][j]=minn+abs(a[i]-b[j]);
        }
    }
    printf("%lld",*min_element(dp[n]+1,dp[n]+1+n));
     return 0;
}

C++11(clang++ 3.9) 解法, 执行用时: 26ms, 内存消耗: 16220K, 提交时间: 2019-07-21 16:21:37

#include<bits/stdc++.h>
using namespace std;
#define N 2005
int n,go[N],hi[N],dp[N][N],i,j,k;
int main()
{
	cin>>n;
	for(i=0;i<n;++i)
		cin>>go[i],hi[i]=go[i];
	sort(hi,hi+n);
	for(i=0;i<n;++i)
		dp[0][i]=abs(hi[i]-go[1]);
	for(i=1;i<n;++i){
		k=dp[i-1][0];	
		for(j=0;j<n;++j){
			k=min(k,dp[i-1][j]);
			dp[i][j]=k+abs(hi[j]-go[i]);
		}
	}
	int ans=dp[n-1][0];
	for(i=0;i<n;++i)
		ans=min(ans,dp[n-1][i]);
	cout<<ans;
	return 0;
}

上一题