问题描述:最长n段连续子序列和
Input
Each test case will begin with two integers m and n, followed by n integers S
1, S
2, S
3 ... S
n.
Process to the end of file.
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
算法思想:
dp[i][j]保存前j个元素(包括j)分成i段最长连续子序列和
则有dp[i][j]=max(dp[i][j-1]+num[j],max(dp[i-1][t]+num[j])) i-1<=t<j
具体思路参见最大子段和问题到最大子矩阵问题(二):最大n子段和问题详谈
#include <iostream>
using namespace std;
int *s;
int m,n;
int maxL;
int *pre,*now;
int main()
{
freopen("C:\\in.txt","r",stdin);
while(scanf("%d %d",&m,&n)!=EOF){
s=new int[n+1];
pre=new int[n+1];
now=new int[n+1];
for(int i=0;i<=n;i++){now[i]=0;pre[i]=0;}
for(int i=1;i<=n;i++){
scanf("%d",&s[i]);
}
for(int i=1;i<=m;i++){
maxL=-0x7fffffff;
for(int j=i;j<=n;j++){
now[j]=(now[j-1]>pre[j-1]?now[j-1]:pre[j-1])+s[j];
pre[j-1]=maxL;
if(maxL<now[j])
maxL=now[j];
}
}
printf("%d\n",maxL);
delete[] s;
}
return 0;
}