简单的dp@poj(2)2479最大子段和

来源:互联网 发布:梦想小镇mac无限绿钞 编辑:程序博客网 时间:2024/05/17 02:29

POJ 2479 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).
(1)状态:left[i]以第i位结尾时最大子串和 Right[i]为以i为间隔位 之后的字符串任何组合的最大字段和
(2)方程:if(left[i-1]<0) left[i]=a[i] else left[i]=left[i-1]+a[i]     同理Right[i]
(3)初值:left[i]=right[i]=a[i]
Attention:在poj如果用cin cout 此题 TLE
#include <iostream>
#include <stdio.h>
using namespace std;
//cin cout »»³Éprintf scanf ¹ýÁË£¡
int main()
{
    int a[50001];
    int left[50001],right[50001],Right[50001];
    int Num,Length;
   scanf("%d",&Num);
    while(Num--)
    {
          scanf("%d",&Length);


        for(int i=1; i<=Length; i++)
        {
              scanf("%d",&a[i]);


            left[i]=right[i]=Right[i]=a[i];
        }
        left[0]=-1;
        right[Length+1]=-1;
        for(int i=1; i<=Length; i++)
        {
            if(left[i-1]>0)
                left[i]=left[i-1]+left[i];
        }
        int r_max=-30000;
        for(int i=Length; i>=1; i--)
        {


            if(right[i+1]>0)
                right[i]=right[i+1]+right[i];
            r_max=right[i]>r_max?right[i]:r_max;
            Right[i]=r_max;
        }
        int max=-30000;
        for(int i=1;i<Length;i++)
        {
            max=left[i]+Right[i+1]>max?left[i]+Right[i+1]:max;


        }
      printf("%d\n",max);
    }
    return 0;
}

原创粉丝点击