Maximum cost of 51nod-1270-arrays
The maximum cost of an array of 1270 arrays A contains n elements A1, A2 ... An. Array B consists of n elements B1, B2 ... BN. And each element of the array, AI, satisfies 1 <= ai <= Bi. The cost of array A is defined as follows: (the formula represents the sum of the absolute values of the difference of all two adjacent elements) given to arrays B, calculating the possible maximum cost S. Input
Line 1th: 1 number N, indicating the length of the array (1 <= n <= 50000). Line 2-n+1:1 numbers per line, corresponding to array element bi (1 <= bi <= 10000).
Output
The maximum cost of output s.
Input example
510110110
Output example
36
Exercises
For a number in an array, there are two options: (1) it itself, (2), 1, so the obvious simple DP problem
Build
The dynamic programming formula: F[i][0] Indicates that the number of I is expressed by himself, F[i][1] indicates that there are 1 of the number of the first I.
There is the formula:
Dp[i][0] = max (Dp[i-1][0]+abs (num[i]-num[i-1]), Dp[i-1][1]+abs (num[i]-1));
DP[I][1] = max (Dp[i-1][0]+abs (1-num[i-1]), dp[i-1][1]);
A simple DP equation
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath& Gt using namespace Std; const int MAXN = 50000; int NUM[MAXN], dp[maxn][2]; int func (int n) {dp[0][0] = dp[0][1] = 0; for (int i=1; i<n; ++i) {dp[i][0] = max (Dp[i-1][0]+abs (num[i]-num[i-1)), Dp[i-1] [1]+abs (Num[i]-1)); DP[I][1] = max (Dp[i-1][0]+abs (1-num[i-1]), dp[i-1][1]); }return Max (dp[n-1][0], dp[n-1][1]); } int main () {freopen ("In.txt", "R", stdin); int n; while (scanf ("%d", &n)! = EOF) {for (int i=0; i<n; ++i) {scanf ("%d", & Amp;num[i]); }int ans = func (n); printf ("%d\n", ans);}}
Maximum cost of 51nod-1270-arrays