[ACM] POJ 2593 Max Sequence (动态规划,最大字段和)

286 篇文章 140 订阅
49 篇文章 0 订阅

Max Sequence
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 15569 Accepted: 6538

Description

Give you N integers a1, a2 ... aN (|ai| <=1000, 1 <= i <= N). 

You should output S. 

Input

The input will consist of several test cases. For each test case, one integer N (2 <= N <= 100000) is given in the first line. Second line contains N integers. The input is terminated by a single line with N = 0.

Output

For each test of the input, print a line containing S.

Sample Input

5
-5 9 -5 11 20
0

Sample Output

40

Source


解题思路:

同 POJ 2479http://blog.csdn.net/sr_19930829/article/details/38397435

题意要求为给定一个数字序列,找出两段不相交的子段,使这两个子段的和最大,求出这个最大值。

dp[i]表示 从位置1到i 之间的最大子段和,正向求一遍。然后逆向求最大子段和,比如逆向求出当前位置i的最大字段和为sum,那么 ans= max( ans,dp[i-1]+sum), ans即为答案。


代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxn=100010;
const int inf=-0x7fffffff;
int dp[maxn];
int num[maxn];
int t,n;

void DP()//正向求最大子段和
{
    memset(dp,0,sizeof(dp));
    int sum=inf,b=inf;
    for(int i=1;i<=n;i++)
    {
        if(b>0)
            b+=num[i];
        else
            b=num[i];
        if(b>sum)
        {
            sum=b;
            dp[i]=sum;
        }
    }
}

int main()
{
    while(scanf("%d",&n)!=EOF&&n)
    {
        for(int i=1;i<=n;i++)
            scanf("%d",&num[i]);
        DP();
        int ans=inf,b=0,sum=inf;//逆向求n到i最大字段和,与正向的最大字段和相加,求出最大值
        for(int i=n;i>1;i--)
        {
            if(b>0)
                b+=num[i];
            else
                b=num[i];
            if(b>sum)
                sum=b;
            if(sum+dp[i-1]>ans)
                ans=sum+dp[i-1];
        }
        printf("%d\n",ans);
    }
    return 0;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值