您的位置:首页 > 其它

poj3666 Making the Grade(dp)

2014-02-06 17:37 525 查看
题目的意思是给出一个序列,要求变成单调不上升或者单调不下降。 代价是 |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: 1000MSMemory Limit: 65536K
Total Submissions: 3813Accepted: 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

USACO 2008 February Gold

代码: (模仿的)

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
#define min(x,y) x<y?x:y
#define INF 0x7fffffff
int N;

int dp[2000+10];
int e[2000+10];
int b[2000+10];
int main()
{
cin>>N;
for(int i=0;i<N;i++)
{
cin>>e[i];
b[i] = e[i];
}
sort(b,b+N);
int ans = INF;
for(int i=0;i<N;i++)
{
int t = INF;
for(int j=0;j<N;j++)
{
t = min(t, dp[j]);
dp[j] = abs( b[j]-e[i]) + t;
}
}
for(int i=0;i<N;i++)
ans = min(ans, dp[i]);
cout<<ans<<endl;
return 0;
}


题目:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: