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 S 1, S 2, S 3, S 4 ... S x, ... S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + ... + S j (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(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + ... + sum(i m, j m) maximal (i x ≤ iy ≤ j x or i x ≤ j y ≤ j x 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(i x, j x)(1 ≤ x ≤ m) instead. ^_^
Input
Each test case will begin with two integers m and n, followed by n integers S 1, S2, 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
Hint
Huge input, scanf and dynamic programming is recommended.
题解:题意是让在n个数中选取m个不相交子串,使子串之和最大。
既然让选m个子串,那就先从一个字串开始找(i=1)最大的和,把每次遍历的最大和更新前赋予dp[i],紧接着(i=2)在(i+1到n)找最大值更新(因为在第一次中每个位置的最大值已经保存),依次循环直到m,就是所求的最大值。
推理:动态规划的思想。
1.基本思路:
首先,定义数组num[n],dp[m][n].
num[n]用来存储n个整数组成的序列.
dp[i][j]用来表示由前 j项得到的含i个字段的最大值,且最后一个字段以num[j]项结尾。仔细想想,我们可以知道:
dp[i][j]=max(dp[i][j-1]+num[j],dp(i-1,t)+num[j]) 其中i-1<=t<=j-1.
(因为必须是以 num[j] 结尾的,所以num[j]一定属于最后一个子段,即要么自己独立成一个子段,要么与前边以num[j-1]结尾的子段联合)
所求的最后结果为 max( dp[m][j] ) 其中1<=j<=n.
但是,我们会发现,当n非常大时,这个算法的时间复杂度和空间复杂度是非常高的,时间复杂度近似为O(m*n^2),
空间复杂度近似为O(m*n).因此,我们需要优化算法来降低时间复杂度和空间复杂度.
2.优化算法:
(1)节省时间
由基本思路,我们可以知道,dp[i][j]=max(dp[i][j-1]+num[j],dp(i-1,t)+num[j]),其中i-1<=t<=j-1.我们只要找到dp[i][j-1]
和dp[i-1][t]的最大值加上num[j]即为dp[i][j].所以,定义一个数组pre_max[n],用pre_max[j-1]来表示求解dp[i][j]时dp[i-1][t]
的最大值,则dp[i][j]=max(pre_max[j-1],dp[i][j-1])+num[j].
特别注意,pre_max[n]这个位置的存储空间是始终用不到的,因此可以用来存储其他数值,在接下来会用到。
在求解dp[i][j]的同时,我们可以计算出dp[i][t];i<=t<=j的最大值,这个最大值在计算dp[i+1][j+1]的时候需要作为pre_max[j]的
形式被使用,我们先把它存在pre_max[n]中。
你可能会问:为什么不把它直接放在pre_max[j]中呢?因为你接下来需要计算dp[i][j+1]的值,需要用到pre_max[j]中原来的值,
如果你把它存在这里,就会覆盖掉计算dp[i][j+1]所需要的那个值。所以,先把它放在pre_max[n]中。
当我们计算完dp[i][j+1]之后,就会发现pre_max[j]中的值已经没有用处了,我们可以把它更新为计算dp[i+1][j+1]所需要的那个值,
即之前放在pre_max[n]中的那个值,即执行pre_max[j]=pre_max[n].
这样我们就节省了计算最大值时付出的时间代价。
(2)节省空间
通过时间的节省,我们突然间发现程序执行结束后pre_max[n]的值即为最后的结果,pre_max[n]数组才是我们希望求解的,
dp[m][n]这个庞大的数组已经不是那么重要了,因此,我们现在用整型数tmp来代替dp[m][n],用来临时存储dp[i][j]的值,
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[1000010],dp[1000010];
int main()
{
int n,m;
while(~scanf("%d%d",&m,&n))
{
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=m;i++)//把从1到M的每阶段都当做一段进行求最大值,每次更新
{ //当i为m时,所得到的最大值就是所求的和
int sum=0;
for(int j=1;j<=i;j++)
sum+=a[j];
dp[n]=sum;
for(int k=i+1;k<=n;k++)
{
sum=max(dp[k-1],sum)+a[k];//每次都把I+1到n的数看做一段
dp[k-1]=dp[n];//每次把最大和存储起来
dp[n]=max(dp[n],sum);//更新当前的最大值
}
}
printf("%d\n",dp[n]);
}
}