HDU 1231:最大連續子序列(DP)

來源:互聯網
上載者:User

標籤:des   style   http   color   java   os   strong   io   

最大連續子序列Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18461    Accepted Submission(s): 8202


Problem Description給定K個整數的序列{ N1, N2, ..., NK },其任意連續子序列可表示為{ Ni, Ni+1, ..., 
Nj },其中 1 <= i <= j <= K。最大連續子序列是所有連續子序列中元素和最大的一個, 
例如給定序列{ -2, 11, -4, 13, -5, -2 },其最大連續子序列為{ 11, -4, 13 },最大和 
為20。 
在今年的資料結構考卷中,要求編寫程式得到最大和,現在增加一個要求,即還需要輸出該 
子序列的第一個和最後一個元素。
 
Input測試輸入包含若干測試案例,每個測試案例佔2行,第1行給出正整數K( < 10000 ),第2行給出K個整數,中間用空格分隔。當K為0時,輸入結束,該用例不被處理。
 
Output對每個測試案例,在1行裡輸出最大和、最大連續子序列的第一個和最後一個元 
素,中間用空格分隔。如果最大連續子序列不唯一,則輸出序號i和j最小的那個(如輸入範例的第2、3組)。若所有K個元素都是負數,則定義其最大和為0,輸出整個序列的首尾元素。 
 
Sample Input
6-2 11 -4 13 -5 -210-10 1 2 3 4 -5 -23 3 7 -2165 -8 3 2 5 01103-1 -5 -23-1 0 -20
 
Sample Output
20 11 1310 1 410 3 510 10 100 -1 -20 0 0HintHint Huge input, scanf is recommended.


HDU1003 max sum一樣的題。。水。。


#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<stdlib.h>#include<vector>#include<queue>#include<cmath>using namespace std;const int maxn = 100000 + 50;int n;int a[maxn];int start;int last;int temp;int ans;int sum;int t;int main(){    while(scanf("%d", &n)==1&&n)    {        t = 0;        memset(a, 0, sizeof(a));        for(int i=1; i<=n; i++)        {            scanf("%d", &a[i]);            if(a[i]<0)            t++;        }        if( t==n ){printf("0 %d %d\n", a[1], a[n]);continue;}        start = 1;        last = 1;        temp = 1;        sum = a[1];        ans = a[1];        for(int i=2; i<=n; i++)        {            if( sum<0 )            {                temp = i;                sum = 0;            }            sum += a[i];            if( sum>ans )            {                ans = sum;                start = temp;                last = i;            }        }        printf("%d %d %d\n", ans, a[start], a[last]);    }    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.