码迷,mamicode.com
首页 > 其他好文 > 详细

Max Sum

时间:2020-02-16 20:25:53      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:out   cout   cin   case   lib   lines   保存   nbsp   pre   

 

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

Sample Output

Case 1:
14 1 4

Case 2:
7 1 6

最大子序列,判断当前这一个数加上前一个数为结尾的最大子序列和以当前的数开头的两个值的大小。

也可以转化为,前一个数为结尾的子序列不小于0,就把当前数加入序列

记录起点,当找到一个大值的时候保存起点和重点

注意格式(笑)

max起始值选择-1001

#include<cstdlib>
#include<iostream>
using namespace std;


int main()
{
    int n = 0;
    cin >> n;
    for (int j = 1; j <= n; j++) {
        int m = 0;
        cin >> m;
        int a[100001] = { 0 };
        for (int i = 1; i <= m; i++) {
            cin >> a[i];
        }
        int temp = 0;
        int t = 1;
        int max = -1001;
        int end = 1;
        int begin = 1;
        for (int i = 1; i <= m; i++) {
            if (temp < 0) {
                temp = a[i];
                t = i;
            }
            else {
                temp += a[i];
            }
            if (temp > max) {
                max = temp;
                begin = t;
                end = i;
            }
        }
        printf("Case %d:\n%d %d %d\n", j, max, begin, end);
        if (j != n) {
            cout << endl;
        }
    }



    return 0;
}

 

Max Sum

标签:out   cout   cin   case   lib   lines   保存   nbsp   pre   

原文地址:https://www.cnblogs.com/Vetsama/p/12318247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!