week12——C-Required questions-3

topic

Dongdong will go to the dormitory to accept the task of sweeping the building every semester and count the number of people in each dormitory.
There are ai individuals in each bedroom (1<=i<=n). From the i-th to the j-th dormitory, there is a total of sum(i,j)=a[i]+…+a[j] individuals.
This makes the dormitory aunt very happy, and has to sweep the building m times. From i to the jth dormitory sum(i,j), the
problem is to find the maximum value of sum(i1, j1) +… + sum(im,jm). And ix <= iy <=jx and ix <= jy <=jx are not allowed. In other words, none of the m segments can intersect.
Note: 1 ≤ i ≤ n ≤ 1e6, -32768 ≤ ai ≤ 32767 The number of people can be negative. . . . (1<=n<=1000000)

Input

Enter m and enter n. Followed by input n ai and processed to EOF

Output

Output maximum sum

Sample Input

1 3 1 2 3
2 6 -1 4 -2 3 -2 3

Sample Output

6
8

Ideas

The state transition equation is dp[i][j]=max(dp[i][j-1]+a[j],dp[i-1][k]+a[j]),dp[i][ j] represents the maximum value of the sum obtained by dividing the first j numbers into i segments. Use the pos array to record the previous maximum value and modify the state equation.

Code

#include<iostream>
#include<string.h>
using namespace std;
const int maxn=1e6+10;
const int INF=0x0fffffff;
int n,m,ans,a[maxn],dp[maxn],pos[maxn];
int main()
{
    
    
	int m,n,ans;
	while(scanf("%d%d",&m,&n)!=EOF)
	{
    
    
		memset(dp,0,sizeof(dp));
		memset(pos,0,sizeof(pos));
		for(int i=1;i<=n;i++)
			scanf("%d",&a[i]);
		for(int i=1;i<=m;i++)
		{
    
    
			ans=-INF;
			for(int j=i;j<=n;j++)
			{
    
    
				dp[j]=dp[j-1]>=pos[j-1]?dp[j-1]:pos[j-1];
				dp[j]+=a[j];
				pos[j-1]=ans;
				ans=ans>=dp[j]?ans:dp[j];				
			}			
		}
		printf("%d\n",ans);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/alicemh/article/details/106149437