题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1024
题目描述:
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.
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的一维数组s中,找出m个互不相交的字串,使得和最大
题目分析:
跟最大和子序列思想相同,只不过这里不再是一个子序列,而是有m个,我们可以很自然地想到用二维dp来解决这个问题,dp[i][j]代表前j个数分成i组,dp[i][j]=max(dp[i][j-1]+v[j],max(dp[i-1][1~j-1]+v[j]);。可是用二维的话会超时,这里就需要我们用背包的思想来简化,另开一组maxx数组来记录前面一段(即i-1段)的最大值。
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int v[1000005],dp[1000005],maxx[1000005],maxnum;
int n,m;
int main()
{
while(scanf("%d%d",&m,&n)!=EOF)
{
for(int i=1;i<=n;i++)
cin>>v[i];
memset(dp,0,sizeof(dp));
memset(maxx,0,sizeof(maxx));
for(int i=1;i<=m;i++)
{
maxnum=-0xfffffff;
for(int j=i;j<=n;j++)
{
//dp[i][j]代表前j个数分成i组
//dp[i][j]=max(dp[i][j-1]+v[j],max(dp[i-1][1~j-1]+v[j]);
dp[j]=max(dp[j-1]+v[j],maxx[j-1]+v[j]);
maxx[j-1]=maxnum;
maxnum=max(maxnum,dp[j]);
}
}
cout<<maxnum<<endl;
}
return 0;
}