您的位置:首页 > 其它

HDU 1024 Max Sum Plus Plus最大m子段和

2015-08-10 19:17 232 查看
Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

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个数,分成不相交的m段。求解最大m子段和。

第一:假定m = 1 ,题简化为最大连续子段和。

设数组为a[i] ; f[1] = 0 ;

简单写出一维动态转移方程 f[i] = max(f[i-1] + a[i] , a[i] );

第二:若m>1 , 则设F[i][j] , 此时定义该数组含义为从第一个数到第i个数(一定包含第i个数)

分成m段的最大和(不一定最优)。

故共有两种决策 1:第i个数和前一个数一起包含在前j段中,则动态转移方程为 F[i][j] = F[i-1][j] + a[i] ;

2: 第i个数独立一段,则F[i][j]= F(j-1 ... i-1)[j-1] + a[i] ;前i-1个元素的最大j-1子段和

故F[i][j]= max(F(j-1 ... i-1)[j-1] ,F[i-1][j] )+a[i] 。

显然,F[i][j]一定包含第i个数,不一定为最优解,故再设G[i][j] : 从第一个到第i个数分成j段的最大和 。

易知状态转移方程:G[i][j] = max(G[i-1][j] ,F[i][j] ) <1>

即从 不含第i个数的最优解G[i-1][j] 与 F[i][j]中选出最大值。

发现 F[i][j]方程中: F(j-1...i-1) [j-1] == G[i-1][j-1] 。 前i个元素的最大j-1子段和为G[i-1][j-1] ,

则前i个(含i)元素的最大j子段和为G[i-1][j-1] + a[i] 。

故F方程化简为 F[i][j]= max(F[i-1][j] , G[i-1][j-1]) + a[i] ; <2>

同样,对于<1>,<2> 同样,我们发现只用到了一层数组,现来考虑优化空间。化简伪代码如下:

for i <- 1 to n

for j <- 1 to (min(m,i))

F[j] = max(F[j] , G[j-1]) + a[i] ;

G[j] = max(G[j] , F[j] ) ;

G[i] = max(G[i],F[j])

代码如下

#include <iostream>
#include <cstdio>
#include <cstring>
#define max(a,b) (a>b?a:b)
const int minn = -1<< 30;
const int maxn = 1000000+100 ;
int f[maxn] , g[maxn] ;
int a[maxn] ;
using namespace std;
int main () {
int  n , m ;
while(~scanf("%d%d",&m,&n)) {
for( int i = 1; i <= n ; ++i ){
scanf("%d",&a[i]) ;
}
for( int i= 0 ; i <= n ; ++i ) {
f[i] =  minn ;
g[i] = minn ;
}
g[0] =  0;
for ( int i = 1 ;i <= n ; ++i ){
int k = i <= m ? i : m ;
for( int j = 1 ; j <= k ; ++j ) {
f[j] = max( f[j] , g[j-1] ) + a[i];
g[j-1] = max( g[j-1] , f[j-1]);
}
g[k] = max(g[k] , f[k]) ;
}
cout << g[m] << endl ;
}

return 0  ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: