码迷,mamicode.com
首页 > 其他好文 > 详细

ACM 动态规划 最大 m 子段和问题(课上)

时间:2016-04-27 15:41:41      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 23976 Accepted Submission(s): 8199


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
 
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
const int MAX = 1e6 + 10;
const int MIN = -1e8;

int curr[MAX], pre[MAX], a[MAX];
int max_sum, n, m;

int main()
{
    while(cin >> m >> n)
    {
        for(int i = 1; i <= n; i++)
            cin >> a[i];
        memset(curr,0,sizeof(curr));
        memset(pre,0,sizeof(pre));
        int j = 0;
        for(int i = 1; i <= m; i++)
        {
            max_sum = MIN;
            for(j = i; j <= n; j++)
            {

                curr[j] = max(curr[j - 1], pre[j - 1]) + a[j];
/*
    pre[j-1]表示的是上一个状态中i...j-1的最大值,
    max_sum更新之后表示的i...j的最大值,所以不能写反了
*/
                pre[j - 1] = max_sum;
                max_sum = max(max_sum, curr[j]);
            }
            //pre[j-1]中始终保持着前一个状态的最大值,这个很重要
            pre[j - 1] = max_sum;
        }
        cout << max_sum << endl;
    }
    return 0;
}

 

ACM 动态规划 最大 m 子段和问题(课上)

标签:

原文地址:http://www.cnblogs.com/lyf-acm/p/5438950.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!