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 ;
}