poj3666 Making the Grade(dp)

题目的意思是给出一个序列,要求变成单调不上升或者单调不下降。 代价是 |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

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

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