NC24960. Making the Grade
描述
输入描述
* 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; }