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 ≤ i y ≤ 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. ^_^
Process to the end of file.
OutputOutput the maximal summation described above in one line.
Sample Input
1 3 1 2 3 2 6 -1 4 -2 3 -2 3Sample Output
6
8
Hint
Huge input, scanf and dynamic programming is recommended.
题目意思为给一个长度为n的序列,给出一个整数m,在序列中取m段不相交的子序列,要求m子段的和最大值
解题思路
设置dp[i][j]为前j个数分成i段的最大值,且最后由第j个数结尾,再设一个数组sum,sum[i][j]表示前j个数分成i段的最大值,不一定是以第j个数结尾,所以我们可以推出状态转移方程dp[i][j] = max(dp[i][j-1]+a[j], sum[i-1][j-1]+a[j]); 由于n比较大,不能开
那么大的二维数组所以需要优化,可以采用滚动数组,之后状态转移方程变为dp[j] = max(dp[j]+a[j], sum[j-1]+a[j]);
代码如下:
#include<stdio.h>
#include<iostream>
#include<string.h>
#define MIN -1000000000
using namespace std;
const int maxn = 1e6 + 10;
int a[maxn];
int dp[maxn], sum[maxn];
int main()
{
int m, n;
while(scanf("%d%d", &m, &n) != EOF)
{
for(int i = 1; i <= n; i ++)
{
scanf("%d", &a[i]);
}
memset(dp, 0, sizeof(dp));
memset(sum, 0, sizeof(sum));
int maxx;
for(int i = 1; i <= m; i ++)
{
maxx = MIN;
for(int j = i; j <= n; j ++)
{
dp[j] = max(dp[j-1]+a[j], sum[j-1]+a[j]);
sum[j-1] = maxx;
maxx = max(maxx, dp[j]);
}
}
//sum[n] = maxx;
printf("%d\n", maxx);
//cout<<endl;
}
return 0;
}