1. 程式人生 > >HDU1231:最大連續子序列

HDU1231:最大連續子序列

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 -2 10 -10 1 2 3 4 -5 -23 3 7 -21 6 5 -8 3 2 5 0 1 10 3 -1 -5 -2 3 -1 0 -2 0
Sample Output 20 11 13 10 1 4 10 3 5 10 10 10 0 -1 -2 0 0 0 Hint
Hint Huge input, scanf is recommended. 思路:最大連續子序列的裸題
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

int a[10005],dp[10005];

int main()
{
    int n,i,j,MAX,cnt;
    while(~scanf("%d",&n),n)
    {
        for(i = 0; i<n; i++)
            scanf("%d",&a[i]);
        int left,right,flag;
        MAX = a[0];
        cnt = 0;
        left = right = a[0];
        for(i = 0; i<n; i++)
        {
            if(cnt<0)
            {
                cnt = a[i];
                flag = a[i];
            }
            else
                cnt+=a[i];
            if(cnt>MAX)
            {
                MAX = cnt;
                left = flag;
                right = a[i];
            }
        }
        if(MAX<0)
        {
            printf("0 %d %d\n",a[0],a[n-1]);
            continue;
        }
        printf("%d %d %d\n",MAX,left,right);
    }


    return 0;
}