您的位置:首页 > 其它

ACM: 动态规划 poj 2479

2016-05-19 23:19 337 查看
                                                                      
Maximum sum

Description
Given a set of n integers:
A={a1, a2,..., an}, we define a function d(A) as below: Your task
is to calculate d(A).
Input

The input consists of
T(<=30) test cases. The number of test cases (T) is
given in the first line of the input.

Each test case contains two lines. The first line is an integer
n(2<=n<=50000). The second line
contains n integers: a1, a2, ..., an. (|ai| <=
10000).There is an empty line after each case.
Output

Print exactly one line for each
test case. The line should contain the integer d(A).
Sample Input

1

10

1 -1 2 2 3 -3 4 -4 5 -5

Sample Output

13

题意: 序列分成两部分, 两部分的连续和再加起来最大的值.

解题思路:

         1. 动态规划. max_left[i]表示左边前i个最大连续和.

                     max_right[i]表示右边前i个最大连续和.

代码:

#include <cstdio>

#include <iostream>

#include <cstring>

using namespace std;

#define MAX 50005

int n;

int a[MAX];

int max_left[MAX];

int max_right[MAX];

int maxsize, temp;

inline int max(int a,int b)

{

    return a > b ?  a : b;

}

int main()

{

    int casenum;

//    freopen("input.txt","r",stdin);

    scanf("%d",&casenum);

    while(casenum--)

    {

        scanf("%d",&n);

        memset(max_left,0,sizeof(max_left));

        memset(max_right,0,sizeof(max_right));

        for(int i = 0; i < n; ++i)

        {

            scanf("%d",&a[i]);

        }

        temp = maxsize = -(1<<29);

        for(int i = 0; i < n; ++i)

        {

            if(temp >= 0)

                temp += a[i];

            else

                temp = a[i];

            maxsize = max(maxsize,temp);

            max_left[i] = maxsize;

        }

       

        temp = maxsize = -(1<<29);

        for(int i = n-1; i >= 0; --i)

        {

            if(temp >= 0)

                temp += a[i];

            else

                temp = a[i];

            maxsize = max(maxsize,temp);

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