poj3666 Making the Grade(dp)

本文探讨了一个经典的算法问题,即如何将一条道路的海拔调整为连续的上升或下降斜坡,以减少牲畜攀爬的难度。通过动态规划的方法,文章详细解释了如何计算最小调整成本的过程,包括对原始序列进行排序和使用DP表来找到最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目的意思是给出一个序列,要求变成单调不上升或者单调不下降。 代价是 |A-B| 的总和

 

网上都是说离散化。。虽然还是不太明白但是这道题终于有点感觉了

 

首先可以看出变化后的序列中所有的数一定还在原数列中, 那么先对原数列排序

 

a                      b1 3 2 4 5 3 9 -> 1 2 3 3 4 5 9

然后dp[i][j]  表示第i个数, 把他变成 b[j] 所要画的最小代价

dp[i][j] = dp[i-1] [ 0~j] + abs(b[j] - a[i])   以此循环。

虽然这道懂了但是感觉这个思路还是有点别扭。。智商拙计。。

 

 

题目:

Making the Grade
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 3813 Accepted: 1784

Description

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

| A 1 - B 1| + | A 2 - B 2| + ... + | 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.

Input

* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer elevation: Ai

Output

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

Sample Input

7
1
3
2
4
5
3
9

Sample Output

3

Source

 
 
代码: (模仿的)
 1 #include <iostream>
 2 #include <cmath>
 3 #include <algorithm>
 4 using namespace std;
 5 #define min(x,y) x<y?x:y
 6 #define INF 0x7fffffff
 7 int N;
 8 
 9 int dp[2000+10];
10 int e[2000+10];
11 int b[2000+10];
12 int main()
13 {
14     cin>>N;
15     for(int i=0;i<N;i++)
16     {
17         cin>>e[i];
18         b[i] = e[i];
19     }
20     sort(b,b+N);
21     int ans = INF;
22     for(int i=0;i<N;i++)
23     {
24         int t = INF;
25         for(int j=0;j<N;j++)
26         {
27             t = min(t, dp[j]);
28             dp[j] = abs( b[j]-e[i]) + t;
29         }
30     }
31     for(int i=0;i<N;i++)
32         ans = min(ans, dp[i]);
33     cout<<ans<<endl;
34     return 0;
35 }

 

 

 

 

题目:

 

转载于:https://www.cnblogs.com/doubleshik/p/3538906.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值