poj 2479 - Maximum sum

题目:找到一个序列中的两个连续段使得他们的和最大。

分析:dp,最大字段和。双向求最大字段和。枚举结束点找到加和最大值。

说明:与合唱队形类似。(同poj2593)(2011-09-24 02:09)

#include <stdio.h>
#include <stdlib.h>

int data[ 50005 ];
int asum[ 50005 ];
int bsum[ 50005 ];

void msum( int *D,int *A, int a, int b, int s )
{
    int sum = 0;
    for ( int i = a ; i != b ; i += s ) {
        if ( sum < 0 ) sum = 0;
        sum += D[ i ];
        A[ i ] = sum;
    }
    int max = A[ a ];
    for ( int i = a+s ; i != b ; i += s )
        if ( max < A[ i ] ) max = A[ i ];
        else A[ i ] = max;
}

int main()
{
    int t,n;
    while ( scanf("%d",&t) != EOF ) 
    while ( t -- ) {
        scanf("%d",&n);
        for ( int i = 1 ; i <= n ; ++ i )
            scanf("%d",&data[ i ]);
            
        msum( data, asum, 1, n, +1 );
        msum( data, bsum, n, 1, -1 );

        int    max = -20000;
        for ( int i = 1 ; i <  n ; ++ i )
            if ( max < asum[ i ] + bsum[ i+1 ] )
                max = asum[ i ] + bsum[ i+1 ];
        
        printf("%d\n",max);
    }
    return 0;
}
 

你可能感兴趣的:(poj 2479 - Maximum sum)