Maximum cost of 51nod-1270-arrays

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.