A-max sum <HDU 1003>

             A-max sum
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.

InputThe 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).
OutputFor 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
给定序列a [1],a [2],a [3] ...... a [n],你的工作是计算一个子序列的最大和。例如,给定(6,-1,5,4,-7),这个序列的最大和为6 +(-1)+ 5 + 4 = 14。
输入的第一行包含一个整数T(1 <= T <= 20),这意味着测试用例的数量。然后是T行,每行以数字N(1 <= N <= 100000)开始,然后是N个整数(所有整数在-1000和1000之间)。
输出对于每个测试用例,你应该输出两行。第一行是“Case#:”,#表示测试用例的编号。第二行包含三个整数,序列中的最大和,子序列的起始位置,子序列的结束位置。如果有多个结果,则输出第一个结果。在两种情况之间输出一个空行。  
 
思路:
求的是一个字序列的最大和 和首尾坐标 定义一个maxsum 因为是连续的 所以单循环求sum值 和maxsum比较大小 如果比maxsum大就更新maxsum 同时 记录初始点和末尾点 因为是从头开始的所以定义k的值是1 而末尾值是i+1(因为i的循环是从0开始) 在sum<0时 更新sum值为0 同时更新k值 因为此时k在之前的末尾后面 所以k=en+1=i+2;
 
#include <iostream>
using namespace std;
int v[100000];
int main()
{
    int m;
    cin>>m;
    for(int q=1;q<=m;q++)
    {
        int n,sum=0,maxsum=-100000,st=0,en=0;
        cin>>n;
        for(int i=0;i<n;i++)
        {
            cin>>v[i];
        }
        int k=1;
        for(int i=0;i<n;i++)
        {
            sum+=v[i];
            if(maxsum<sum)
            {
                maxsum=sum;
                en=i+1;
                st=k;
            }
            if(sum<0)
            {
                sum=0;//当sum<0时 更新sum为0;
                k=i+2;
            }
        }
        cout<<"Case "<<q<<":"<<endl;
        cout<<maxsum<<" "<<st<<" "<<en<<endl;
        if(q!=m)
            cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xuxua/p/9275325.html