最大子序列

Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
 

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
 

Sample Input
2

5 6 -1 5 4 -7

7 0 6 -1 1 -6 7 -5
 
解题思路:解题思路:输入一串整数,记一个最大和summax,使其不断与前i个数的和比较若sum[i]>summax并记录开始与结束的位置,则使summax=sum[i];若sum[i]<0,则sum[i]=0并记录此时的位置为起始位置;此后不断循环最终得到所求结果。注意起始位置的记录。

经典的动态规划题目,

#include <iostream>
using namespace std;

int main(){
    int a[100002];
    int t,c;
    cin >> t;
    for (int i=0; i<t; i++) {
        cin >> c;
        int summax=-1000;
        int sum=0,st=0,end=0,k=1;
        for (int i=0; i<c; i++) {
            cin >> a[i];
        }
        for (int i=0; i<c; i++) {
            sum+=a[i];
            if (summax<sum) {
                summax=sum;
                st=k;
                end=i+1;
            }
            if (sum<0) {
                sum=0;
                k=i+2;
            }
        }
        cout << "Case " << i+1 <<endl <<summax << " " << st << " " << end << endl;
        if ((i+1)!=t) {
            cout << endl;
        }
        
    }
    return 0;
}

 

posted @ 2019-09-10 21:07  QianweiZ  阅读(551)  评论(0编辑  收藏  举报