Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 21290 Accepted Submission(s): 7111
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.
题意是给n个数S1,S2,S3,S4…Sn,并且定义sum(i,j)=Si+…+Sj。
给一个数m(并没有给范围,但是一定比较小,大了真心AC不了),任务是去找到m个不交叉的区间(i,j),使得sum(i1,j1)+sum(i2,j2)+…sum(im,jm)最大。
最后输出这个最大值。
n在10^6内,Sn在int范围内,m范围未给出。
用dp[i][j]来表示在最后一个区间包含第j个数的前提下,在前j个数中取i个区间的最大和;
用pre[i][j]来表示在前j个数中取i-1个区间的最大和,不包含第j个数;
那么动态方程就应该是
dp[i][j]=max(dp[i][j-1]+Sj,pre[i][j]+Sj)
由于n的范围比较大,直接存的话会爆,使用滚动数组。
dp[j]、pre[j]就代表当前已划分i-1个区间,正要划分第i个区间时的存储。
在这里我为了省去不必要的memset以节省时间,第一个区间的值的计算单独列出来写,相比之前的代码还是省了耗时的。
//
// main.cpp
// 基础DP1-A-Max Sum Plus Plus
//
// Created by 袁子涵 on 15/10/22.
// Copyright © 2015年 袁子涵. All rights reserved.
//
// 327ms 2752KB
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#define INF 1000005
#define MAX 0x7fffffff
using namespace std;
long long int n,m;
int s[INF],dp[INF],pre[INF],temp;
int main(int argc, const char * argv[]) {
while (scanf("%lld%lld",&m,&n)!=EOF) {
dp[0]=0;
temp=-MAX;
for (long long int j=1; j<=n; j++) {
scanf("%d",&s[j]);
dp[j]=max(dp[j-1]+s[j],s[j]);
pre[j-1]=temp;
temp=max(temp,dp[j]);
}
for (long long int i=2; i<=m; i++) {
temp=-MAX;
for (long long int j=i; j<=n; j++) {
dp[j]=max(dp[j-1]+s[j],pre[j-1]+s[j]);
pre[j-1]=temp;
temp=max(temp,dp[j]);
}
}
printf("%d\n",temp);
}
return 0;
}