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.
不得不说逆推真的很强大。。
从低到上。。问你怎么能最快到达。。
#include<stdio.h> #include<string.h> #include<algorithm> #include<vector> #define N 20000 #define inf 0x3f3f3f3f using namespace std; int n,x,y,Max; struct data { int l,r,h; bool operator <(const data &a)const { return h<a.h; } }a[100003]; int dp[N][2]; void leftoper(int i) { int k=i-1; while(k>0&&a[i].h-a[k].h<=Max) { if(a[k].l<=a[i].l&&a[k].r>=a[i].l) { dp[i][0]=a[i].h-a[k].h+min(a[i].l-a[k].l+dp[k][0],a[k].r-a[i].l+dp[k][1]); return; } k--; } if(a[i].h-a[k].h>Max) dp[i][0]=inf; else dp[i][0]=a[i].h; } void rightoper(int i) { int k=i-1; while(k>0&&a[i].h-a[k].h<=Max) { if(a[k].l<=a[i].r&&a[k].r>=a[i].r) { dp[i][1]=a[i].h-a[k].h+min(a[i].r-a[k].l+dp[k][0],a[k].r-a[i].r+dp[k][1]); return; } k--; } if(a[i].h-a[k].h>Max) dp[i][1]=inf; else dp[i][1]=a[i].h; } int main() { int T; scanf("%d",&T);///啦啦啦啦 while(T--) { //memset(dp,0x3f3f3f3f,sizeof(dp)); scanf("%d%d%d%d",&n,&x,&y,&Max); a[0].l=x; a[0].r=x; a[0].h=y; for(int i=1;i<=n;i++) { scanf("%d%d%d",&a[i].l,&a[i].r,&a[i].h); } a[n+1].l=-N; a[n+1].r=N; a[n+1].h=0; sort(a,a+2+n); dp[0][0]=1; dp[0][1]=1; for(int i =1 ;i<=n+1;i++) { leftoper(i); rightoper(i); } printf("%d\n",max(dp[n+1][0],dp[n+1][1])); } }