Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 26559 Accepted Submission(s): 9230
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
Hint
Huge input, scanf and dynamic programming is recommended.
Author
JGShining(极光炫影)
问题很简单 就是n个数 求最大m段和
很久前就看到过这题 当时因为m没给范围 考虑了下复杂度就没做了
真正动手试试 其实这题数据并不大 O(m*n)也是可以AC的
d[i][j][0] = 前i个数中 选出j段 而且 第i个数没有被用上
d[i][j][1] = 前i个数中 选出j段 而且 第i个数被用上了
d[i][j][0] = max(d[i-1][j][0],d[i-1][j][1]);
d[i][j][1] = max(d[i-1][j-1][0],d[i-1][j-1][1],d[i-1][j][1]);
d[0][0][0]=0;
d[0][0][1]=-inf;
d[0][j][k]=-inf; //j>0 k=0,1
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<vector>
#include<deque>
#include<queue>
#include<algorithm>
#include<set>
#include<map>
#include<stack>
#include<time.h>
#include<math.h>
#include<list>
#include<cstring>
#include<fstream>
//#include<memory.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<int,int>
#define INF 1000000007
#define pll pair<ll,ll>
#define pid pair<int,double>
const int N=1000000+5;
int elem[N];
const ll inf=1e18;
ll d[2][N][2];
ll dp(int m,int n){
ll(*d1)[2]=d[0];
ll(*d2)[2]=d[1];
for(int i=0;i<=n;++i){
d1[i][0]=d1[i][1]=-inf;
}
d1[0][0]=0;
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
d2[j][0]=max(d1[j][0],d1[j][1]);
d2[j][1]=max(d1[j-1][0]+elem[i],
max(d1[j][1]+elem[i],d1[j-1][1]+elem[i]));
}
swap(d1,d2);
}
return max(d1[m][0],d1[m][1]);
}
int main()
{
//freopen("/home/lu/文档/r.txt","r",stdin);
//freopen("/home/lu/文档/w.txt","w",stdout);
int m,n;
while(~scanf("%d%d",&m,&n)){
for(int i=1;i<=n;++i){
scanf("%d",&elem[i]);
}
printf("%lld\n",dp(m,n));
}
return 0;
}