NC51153. 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
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); }