HDU1003-dp(大概)


题目

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. 

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. 

Examples

Input

2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5

Output

Case 1:
14 1 4

Case 2:
7 1 6

思路

这个题目可以把计算过的前部分看成一个整体(一个数字),如果发现这个整体的和小于0,就从下一个数字重新开始加(因为前面的和为负数,我们要求最大和,加上的话反而和会变小),咋这个过程中,不断更新和的最大值,即可得到答案。

代码

#include<stdio.h>
int main()
{
    long long max,n,sum;
    //freopen("F:/y.txt","r",stdin);
    int T;
    scanf("%d",&T);
    for(int t=1;t<=T;t++)
    {
       scanf("%lld",&n);
       int l1=1,l=1,r=1;
       sum=0;
       max=0;
       int f=1;
       long long x;
       for(int i=1;i<=n;i++)
       {
           scanf("%lld",&x);
           if(i==1)
           max=x;
           sum+=x;
           if(sum>max)
           {
              max=sum;
              l=l1;
              r=i;
           }
           if(sum<0)
           {
              sum=0;
              l1=i+1;
           }
       }
       printf("Case %d:\n",t);
       printf("%lld %d %d\n",max,l,r);
       if(t!=T)
       printf("\n");
    }
    return 0;
}

文章作者: xucanxx
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 xucanxx !
  目录