A - Max Sum

Given a sequence a11,a22,a33......ann, 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,如果和小于0,则更新起点的位置.
 
 
 
 
 
 
 
 




代码实现:
 
 
 
 
#include<bits/stdc++.h>
using namespace std;
int a[1000005];
int main()
{
    int t,j,i,n;
    scanf("%d",&t);//输入样例组数.
    for(j=1;j<=t;j++)
    {
        scanf("%d",&n);//输入有多少个数字。
        for(i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        int sum=0;//记录和;
        int start;//记录开始位置;
        int temp=1;//初始化的开始位置从1开始
        int end;//记录结束位置;
        int max_sum=-100000;//因为要判断是否加的数更大,所以设置一个很小的值
        for(i=0;i<n;i++)//一个一个的判断是否和更大
        {
            sum=sum+a[i];
            if(sum>max_sum)//如果和大,表示加的数更大;
            {
                max_sum=sum;
                start=temp;//起点位置
                end=i+1;//终点位置
            }
            if(sum<0)//如果和小于0了,说明不是和最大的子序列,重置sum,把起始位置更新
            {
                sum=0;
                temp=i+2;
            }
        }
        printf("Case %d:\n",j);//输出答案即可
        printf("%d %d %d\n",max_sum,start,end);
        if(j!=t)
            printf("\n");//因为题目中要求两组输入之间要空行,所以判断是否为最后一组测试样例(我在编写时因没注意导致PE
    }
    return 0;
}


 
 
 
 
 
 
 
 
 
 
 
 
 

猜你喜欢

转载自blog.csdn.net/qq_37422760/article/details/74855017