【兩段連續不重合子序列和最大】 動態規劃

來源:互聯網
上載者:User

標籤:des   style   blog   color   io   os   for   sp   div   

最大子序列

TimeLimit: 1 Second MemoryLimit: 32 Megabyte

Totalsubmit: 156 Accepted: 42

Description

給定一個N個整數組成的序列,整數有正有負,找出兩段不重疊的連續子序列,使得它們中整數的和最大。兩段子序列都可以為空白。

Input

多組輸入,每組第一行為N,表示序列的長度;第二行為N個整數,表示輸入序列。
0<N<=1,000,000

Output

對於每組輸入,輸出一行,僅一個整數,表示最大的和。

Sample Input

9
185 -580 -889 701 964 -878 353 -761 608

Sample Output

2273

Hint

範例輸入序列的一種選擇為:(701 964)和(608),整數的範圍為(-1000,1000)

 

 

#include <iostream>#include <cstdio>using namespace std;const int INF=1000005;int s[INF],lt[INF],rt[INF],dp[INF];int main(){    //freopen("in.txt","r",stdin);    int i,n;    while(cin >> n)    {        for (i=1;i<=n;i++)scanf("%d",&s[i]);        dp[n+1]=dp[0]=-INF;        lt[0]=rt[n+1]=-INF;        for (i=1;i<=n;i++)//正向        {            dp[i] = max(dp[i-1]+s[i],s[i]);        }         for (i=1;i<=n;i++)         {             lt[i] = max(dp[i],lt[i-1]);//             lt[i] = dp[i];         }        for (i=n;i>=1;i--)  //逆向        {            dp[i] = max(dp[i+1]+s[i],s[i]);        }         for (i=n;i>=1;i--)         {             rt[i] = max(dp[i],rt[i+1]);//                rt[i] = dp[i];         }         int sum=-INF;//枚舉        for (i=1;i<=n;i++)        {            sum = max(sum,lt[i]+rt[i+1]);        }        if(sum<=0)        cout <<‘0‘ <<endl;        else printf("%d\n",sum);    }    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.