Problem Description
Now I think you have got an AC in Ignatius.L’s “Max Sum” problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem.
Given a consecutive number sequence S1, S2, S3, S4 … Sx, … Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + … + Sj (1 ≤ i ≤ j ≤ n).
Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i1, j1) + sum(i2, j2) + sum(i3, j3) + … + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx is not allowed).
But I`m lazy, I don’t want to write a special-judge module, so you don’t have to output m pairs of i and j, just output the maximal summation of sum(ix, jx)(1 ≤ x ≤ m) instead. ^_^
Input
Each test case will begin with two integers m and n, followed by n integers S1, S2, S3 … Sn.
Process to the end of file.
Output
Output the maximal summation described above in one line.
Sample Input
1 3 1 2 3
2 6 -1 4 -2 3 -2 3
Sample Output
6
8
题意:
输入m,n,代表n个数字分成m段不相交的子段,求这m段不相交的子段最大和是多少。
思路:
dp[i][j]代表j个数字分成i段的最大和,且包含a[j]。
dp[i][j]=max(dp[i-1][k]+a[j],dp[i][j-1]+a[j]) (0< k< j)
意思是a[j]单独成一段和不单独成一段
下图是dp[i][j]的来源
所以一维dp[j]=max(dp[k]+a[j],dp[j-1]+a[j]),只不过前者是上一层,后者是下一层。设lastmax[i]保存上一层dp[1]-dp[i-1]中的最大值,所以dp[j]=max(lastmax[j]+a[j],dp[j-1]+a[j]),代码如下。
#include<bits/stdc++.h>
using namespace std;
const int N = 1000005;
int dp[N],lastmax[N],a[N];
int main()
{
int n,m,i,max1;
while(~scanf("%d%d",&m,&n))
{
for(i=1; i<=n; i++)
scanf("%d",&a[i]);
memset(lastmax,0,sizeof(lastmax));
memset(dp,0,sizeof(dp));
for(int j=1; j<=m; j++)
{
max1=-1e9;//max1是lastmax[j-1]
for(i=j; i<=n; i++)
{
dp[i]=max(dp[i-1],lastmax[i-1])+a[i];
lastmax[i-1]=max1;
max1=max(max1,dp[i]);
}
}
printf("%d\n",max1);
}
return 0;
}