题目:
Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36636 Accepted Submission(s): 13050
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个不重合的组使得这m组数的和最大。
题解:这个题用动态规划解决, 简单来想可以用dp[i][j]表示前j 项找出i 组的最大值, 这样来定义递推关系。
有: dp[i][j] = max(dp[i][j - 1] + s[j] , max(dp[i - 1][k] + s[j])), 每遇到一个数字都有两种情况:
(1)将其加入到第i 组中不增加新组。
(2)将s[j]单独列成第i组, 寻找 前i - 1组中的最大值加起来。
取上述两种情况的最大值。
仔细看看不难发现max(dp[i - 1][k])就是上一组0 到 j - 1的最大值, 可以在每次循环时开一个maxx数组记录下下次要用的最大值。计算中只需要当前行以及上一行的数据, 因此这样数组可以优化到一维, 时间优化到O(n ^ 2)。
AC代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int dp[1000005] = {0};//分组划分过程中计算只需要当前行和上一行, 因此数组只需要一维
int maxx[1000005] = {0};//用来存下上个分组中前j - 1项的最大值
int s[1000005];
int main()
{
int i, j, n, ans, ma, m, k;
while(~scanf("%d %d", &m, &k)){
for(i = 1;i <= k;i++)
scanf("%d", &s[i]);
for(i = 1;i <= m;i++){//分成i组
ans = -99999999;//赋ans最小值
for(j = i;j <= k;j++){//枚举分组起点,分成i组至少要i个元素
dp[j] = max(dp[j - 1] + s[j], maxx[j - 1] + s[j]);//两种情况的状态转移
maxx[j - 1] = ans;//记录此次分组中前j - 1项的最大值
ans = max(ans, dp[j]);//更新答案
}
}
printf("%d\n", ans);
memset(maxx, 0, sizeof(maxx));
memset(dp, 0, sizeof(dp));
}
return 0;
}
点个赞吧~~谢谢。