Max Sum HDU - 1003(最大子序列和)

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,若大于0,令此时最大和等于第一个元素的值,若小于0,则舍去第一个元素,此时最大和为0,要注意下标的变化,然后依次相加,同理,若和为负数,则归为0,更新下标,若此时和加上后面的一个数变小了,则此时说明和最大的子序列已经到了结束的时候了,记录坐标,注意输出格式!

代码:

#include<stdio.h>
int main()
{
    int t,k=0;
    scanf("%d",&t);
    while(t--)
    {
        k++;
        int n,a,s;
        scanf("%d",&n);
        scanf("%d",&a);
        s=a;
        int i,b,c=1,head=1,tail=1;
        for(i=2; i<=n; i++)
        {
            scanf("%d",&b);
            if(s<0)
            {
                s=0;
                c=i;
            }
            s=s+b;
            if(s>a)
            {
                a=s;
                head=c;
                tail=i;
            }
        }
        if(k==1)
        {
            printf("Case %d:\n",k);
            printf("%d %d %d\n",a,head,tail);
        }
        else
        {
            printf("\nCase %d:\n",k);
            printf("%d %d %d\n",a,head,tail);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Piink/article/details/105605048