[ACM] POJ 2593 Max Sequence (動態規劃,最大欄位和)

來源:互聯網
上載者:User

標籤:acm   動態規劃   

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 200

Sample Output

40

Source

POJ Monthly--2005.08.28,Li Haoyuan


解題思路:

同 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;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.