1. 程式人生 > >PAT Maximum Subsequence Sum[最大子序列和,簡單dp]

PAT Maximum Subsequence Sum[最大子序列和,簡單dp]

ace 序號 fin nts 很好 lag malle test 二次

1007 Maximum Subsequence Sum (25)(25 分)

Given a sequence of K integers { N~1~, N~2~, ..., N~K~ }. A continuous subsequence is defined to be { N~i~, N~i+1~, ..., N~j~ } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10
-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4


#include <iostream>
#include <cstring>
#include <cstdio>
#include<map>
#include<stack>
using namespace std;
int sz[10001];
int main()
{

    //freopen("1.txt","r",stdin);
    //就是尋找最大和序列。我之前見過這種題,不過現在忘記了。
    //第一次提交12分。。。到底是哪裏錯了?
    //沒有最小值的沒有考慮到。。
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>sz[i];
    }
    int maxs=-1,thiss=0;
    int f=0,e=n-1,temp=0;
    for(int i=0;i<n;i++){
        thiss+=sz[i];
        if(thiss>maxs){
            maxs=thiss;
            e=i;
            f=temp;
        }else if(thiss<0){
            thiss=0;
            temp=i+1;
        }//這怎麽標記開始和結束啊?。。。。
        //cout<<thiss<<" "<<sz[i]<<" "<<f<<" "<<e<<‘\n‘;
        }
    if(maxs<0)//第二次提交加上這個之後,得分還是12;使用了flag判斷之後依舊是12分。。
        maxs=0;
    cout<<maxs<<" "<<sz[f]<<" "<<sz[e];

    return 0;
}

//emmm,這個整了有2h.第一次提交12分,主要是不太會標記開始,結束很好標記。後來提交22分,還差3分。發現主要是對數據

2

0 -1 這樣的,因為我的maxs初始化為0,那麽就無法進行更新。所以初始化為了-1。

//最大子序列和問題,O(n)內的問題就可以解決,順序相加,每次都比較是否比之前的最大和大;如果出現了負值和,那肯定就不能有貢獻。初始化為0.此時也標記一個新的開始,如果本次開始和序列值出現了最大,那麽就會更新開始位置序號。懂了。

//還要註意讀題,最大序列和為負值時要輸出0和n-1位置的數字,這是題目給的。

PAT Maximum Subsequence Sum[最大子序列和,簡單dp]