Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 30478 Accepted Submission(s): 10750
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 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. ^_^
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.
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
这题的题意:
设输入的数组为a[1...n],从中找出m个段,使者几个段的和为最大;
dp[i][j]表示前j个数中取i个段的和的最大值,其中最后一个段 包含a[j]。
dp[i][j]=max(dp[i][j-1],dp[i-1][k])+a[j], 前一个表示j与j-1在i组里,后一个表示j单独成组。 这个代码会爆内存。
#include#include #include #include using namespace std;int dp[1000][1000];int main(){ int n,m; int a[100000]; while(cin>>n>>m) { for(int i=0;i >a[i]; memset(dp,0,sizeof dp); for(int i=1;i<=n;i++) { for(int j=0;j
n 1,000,000,m不知道,开一个2维dp数组会炸内存。
那么我们用 一个滚动数组去更新
因为
dp[i][j]=max(dp[i][j-1],dp[i-1][k])+a[j], 第i个区间之和i-1一个有关 那么dp[t][j]=max(dp[t][j-1],dp[1-t][k])+a[j];
#includeusing namespace std;int dp[2][100000];int main(){ int n,m; int a[100000]; while(cin>>n>>m) { for(int i=0;i >a[i]; memset(dp,0,sizeof dp); int t; for(int i=1;i<=n;i++) { t=i%2; for(int j=0;j
你以为换完滚动数组就好了吗。不纯在的。超时
现在这个算法是n的3次方
那我们就要想用快一点的
考虑我们不需要j-1之前的最大和具体发生在k位置,只需要在j-1处记录最大和即可用pre[j-1]记录即可
pre[j-1],不包括a[j-1]的j-1之前的最大和
则dp[t][j]=max(dp[t][j-1],pre[j-1])+a[j]
此时可以看见,t这一维也可以去掉了
即最终的状态转移为
dp[j]=max(dp[j-1],pre[j-1])+a[j];
#include#include #include #include using namespace std;int dp[100005];int pre[100005];int main(){ int n,m; int a[100005]; while(~scanf("%d%d",&n,&m)) { for(int i=1;i<=m;i++) scanf("%d",&a[i]); memset(dp,0,sizeof dp); memset(pre,0,sizeof pre); int mx; for(int i=1;i<=n;i++) { mx=-999999999; for(int j=i;j<=m;j++) { dp[j]=max(dp[j-1],pre[j-1])+a[j]; pre[j-1]=mx; mx=max(mx,dp[j]); } } printf("%d\n",mx); } return 0;}