杭電 1231 最大連續子序列

來源:互聯網
上載者:User

標籤:杭電

http://acm.hdu.edu.cn/showproblem.php?pid=1231

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


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.

AC代碼:

#include<iostream>#include<cstring>#include<cstdio>using namespace std;#define M 100005int a[M];int main(){    int  n;    while(~scanf("%d",&n) && n)    {        int ans,max,i,x1,y1,p,k=0;        scanf("%d",a+1);        if(a[1]<0)   k++;        ans=max=a[1];        x1=y1=p=1;        for(i=2;i<=n;i++)        {            scanf("%d",a+i);            if(a[i]<0)  k++;            if(ans<0)                ans=a[i],p=i;            else                ans+=a[i];            if(max<ans)                max=ans,x1=p,y1=i;        }        if(k==n)            printf("%d %d %d\n",0,a[1],a[n]);        else            printf("%d %d %d\n",max,a[x1],a[y1]);    }    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.