POJ 3666 Making the Grade

Making the Grade

Time Limit: 1000ms
Memory Limit: 65536KB
This problem will be judged on PKU. Original ID: 3666
64-bit integer IO format: %lld      Java class name: Main

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

 
解题:注意到数据范围较大,离散化高度。。。不是直线增加高度了。。。。由于dp[i][k] = min(dp[i-1][j]) + abs(B[k] - A[i])
 
每次都是从i-1转移过来,所以不需要滚动数组都行
 
abs中的内容表示当前要处理的东东的高度是A[i],让他变成高度B[k]
 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 using namespace std;
 7 typedef long long LL;
 8 const int maxn = 2010;
 9 const int INF = 0x3f3f3f3f;
10 int dp[maxn],A[maxn],B[maxn];
11 int main() {
12     int n;
13     while(~scanf("%d",&n)) {
14         memset(dp,0,sizeof dp);
15         for(int i = 0; i < n; ++i) {
16             scanf("%d",A+i);
17             B[i] = A[i];
18         }
19         sort(B,B+n);
20         int ret = INF;
21         for(int i = 0; i < n; ++i) {
22             int minV = INF;
23             for(int j = 0; j < n; ++j) {
24                 minV = min(minV,dp[j]);
25                 dp[j] = abs(B[j] - A[i]) + minV;//第i个东东变成高度为B[j]
26                 if(i + 1 == n) ret = min(ret,dp[j]);
27             }
28         }
29         printf("%d
",ret);
30     }
31     return 0;
32 }
View Code