The maximum number of paragraphs and this is the classic problem of dynamic planning, the previous talk about a simple dynamic programming problem, the largest sub-segment and not difficult, we mainly through these simple questions to understand the dynamic planning. There are also the largest sub-segments and the use of divide-and-conquer method can also be done, until later we are talking.
Problem Description: A sequence of n integers (possibly negative numbers) a[1],a[2],a[3],..., A[n], and the maximum value of the sub-segments of the sequence, such as A[i]+a[i+1]+...+a[j].
When the given integer is negative, the sub-segment is defined and is 0.
Solution Ideas:
Before you say it, dynamic planning solves the problem from the bottom up. The size of the original problem is n meta
Of These n elements are not considered, we first consider n-1 elements, so it is not good to test
Consideration, we consider n-2 elements, which in turn decrements, and finally the problem scale becomes a
Elements. But we find that in the process of decreasing, the optimal solution of sub-problem contains
In the optimal solution of the original problem, and some of the solutions of the sub-problems are repeated.
Therefore, use dynamic planning to solve this problem.
As mentioned in the previous blog post, we're going to write a recursive equation. We set up an array B to hold the optimal solution, first storing the b[1]=a[1],a as our n elements. The first element, his state is to put him in the array B (and some of the previous image). So the recursive equation is: b[i]=max{b[i-1]+a[i],a[i]}.
For example: There is a set of numbers, such as 2 5 4-3 7 The maximum child segment and is 13, which is from 5 to 7.
Code:
#include <stdio.h>
#define N-
a[n];
int main ()
{
int i,n,b[n],max;
while (scanf ("%d", &n) &&n!=0)
{
for (i=1;i<=n;i++)
scanf ("%d", &a[i]);
B[1]=A[1];
for (i=2;i<=n;i++)
{
if (b[i-1]>0)
b[i]=b[i-1]+a[i];
else
b[i]=a[i];
}
MAX=B[1];
for (i=1;i<=n;i++)
if (Max<b[i])
max=b[i];
printf ("%d\n", max);
}
return 0;
}
Here, if we ask for the output to be those numbers, what should we do?
We just need to set up an array of C, to hold those books that make up the largest sub-segments and. When I put the I into B, we put the corresponding I into C, and finally output C can be. The code is not written, I hope you realize.