HDU 1024 Max sum plus

Source: Internet
Author: User

Hdu_1024

You can use F [I] [J] to represent the optimal solution for scanning the J element and selecting the I range in total, in this way, F [I] [J] = max {f [I] [J-1], f [I-1] [k] + A [J]-A [k]} (I-1 <= k <j) where a [] represents the prefix and.

If optimization is not added, it is O (Mn ^ 2 ).AlgorithmBut in fact we can maintain the maximum value of X = F [I-1] [k]-A [k] In the recursive process, then the dynamic transfer equation is rewritten to f [I] [J] = max {f [I] [J-1], x + A [J]}, so that O (Mn) complexity.

In addition, you can use a scrolling array to save space.

# Include <stdio. h>
# Include < String . H>
# Define Maxd 1000010
# Define INF has been 0000000ll
Int N, m;
Long Long Int A [maxd], wa [maxd], WB [maxd], * a, * B;
Void Init ()
{
Int I, J, K;
A [ 0 ] = 0 ;
For (I = 1 ; I <= N; I ++)
{
Scanf ( " % D " , & K );
A [I] = A [I- 1 ] + K;
}
}
Void Solve ()
{
Int I, J, K;
Long Long Int * T, x;
A = wa, B = WB;
For (I = 0 ; I <= N; I ++)
B [I] = 0 ;
For (I = 1 ; I <= m; I ++)
{
A [I- 1 ] =-INF;
X = B [I- 1 ]-A [I- 1 ];
For (J = I; j <= N; j ++)
{
A [J] = A [J- 1 ];
If (X + A [J]> A [J])
A [J] = x + A [J];
If (B [J]-A [J]> X)
X = B [J]-A [J];
}
T = A, A = B, B = T;
}
Printf ( " % I64d \ n " , B [N]);
}
Int Main ()
{
While (Scanf ( " % D " , & M, & n) = 2 )
{
Init ();
Solve ();
}
Return 0 ;
}


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.