sdut-1351-Max Sum-hdu-1003

来源:互联网 发布:明道办公软件登陆 编辑:程序博客网 时间:2024/06/02 05:06

题目描述

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.

输入

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).

输出

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.

示例输入

25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5

示例输出

Case 1:14 1 4Case 2:7 1 6


#include<stdio.h>#include<string.h>#include<stdlib.h>int ls[100005];int begin[100005];int main(){    int t;    scanf("%d",&t);     for(int r = 1; r<=t; r++)    {        int n;        scanf("%d",&n);        int i;        for(i = 1; i <= n; i++)            scanf("%d",&ls[i]);        int max= 0, sum = 0;        int top = 0, end = 1;        max = ls[1];        sum = ls[1];        begin[++top] = 1;        for(i = 2; i <= n; i++)        {            sum += ls[i];            if(sum >= max)            {                end = i;                max = sum;            }            else if(sum < 0)            {                sum = 0;                begin[++top] = i+1;            }        }        printf("Case %d:\n",r);        while(begin[top]>end)        {            top--;        }        if(r < t)        {            printf("%d %d %d\n",max,begin[top],end);            printf("\n");        }        else        {            printf("%d %d %d\n",max,begin[top],end);        }    }    return 0;}


0 0
原创粉丝点击