hdu–1231–最長子序列(DP)

來源:互聯網
上載者:User
最大連續子序列

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15620    Accepted Submission(s): 6842

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
    

最大連續子序列,這應該算一道簡單的動態規劃題,重要的是找狀態轉移方程,這題的狀態轉移方程是:

if(maxsum[i-1]>=0)maxsum[i]=a[i]+maxsum[i-1];elsemaxsum[i]=a[i];

 代碼:

#include<stdio.h>#include<string.h>#include<stdlib.h>struct MAX{    int sum,start,end;    }max[10001];int main(){int a[10001];int n,i,Max,d;while(scanf("%d",&n),n){memset(max,0,sizeof(max));for(i=1; i<=n; i++){scanf("%d",&a[i]);}max[1].sum=a[1];max[1].start=1;max[1].end=1;for(i=2; i<=n; i++){if(max[i-1].sum>=0){max[i].sum=max[i-1].sum+a[i];max[i].start=max[i-1].start;max[i].end=i;}else{max[i].sum=a[i];max[i].start=i;max[i].end=i;}}Max=max[1].sum;d=1;for(i=2; i<=n; i++){if(max[i].sum>Max){Max=max[i].sum;d=i;}}if(Max<0){printf("0 %d %d\n",a[1],a[n]);continue;}else{printf("%d %d %d\n",Max,a[max[d].start],a[max[d].end]);}}        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.