首页 > 其他 > 详细

最大子序列

时间:2019-09-10 22:16:18      阅读:80      评论:0      收藏:0      [点我收藏+]

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;
}

 

最大子序列

原文:https://www.cnblogs.com/zhouqianwei/p/11502928.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!