程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> poj 3666 Making the Grade (動態規劃)

poj 3666 Making the Grade (動態規劃)

編輯:關於C++

 

Making the Grade Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 4647   Accepted: 2202

 

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

一個想法是:對於a[i],枚舉任一高度作為最大高度,取前i-1個的合法最優解。

數據范圍很大10^9,但n只有2000大小,可以離散化,用坐標代替高度。

a[i]存原始數組,b[j]存排序後遞增的數組。

dp[i][j]=min(dp[i-1][0..j])+abs(a[i]-b[j]); (把第i 個數高度改為b[j],此時的最小成本。)

 

 

#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define ll __int64
#define mem(a,t) memset(a,t,sizeof(a))
#define N 2005
const int M=305;
const int inf=0x7fffffff;
int a[N],b[N];
int dp[N];
void solve(int n)
{
    int i,j,tmp;
    sort(b,b+n);
    for(i=0;i

 

 

 

 

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved