hdu.Max Sum

Problem Description

Given a sequencea[1],a[2],a[3]......a[n], your job is to calculate the max sum of asub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is6 + (-1) + 5 + 4 = 14.

Input

The first line of the input contains aninteger T(1<=T<=20) which means the number of test cases. Then T linesfollow, each line starts with a number N(1<=N<=100000), then N integersfollowed(all the integers are between -1000 and 1000).

Output

For each test case, you should outputtwo lines. The first line is "Case #:", # means the number of thetest case. The second line contains three integers, the Max Sum in thesequence, 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 linebetween 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

 

求最大子列;

如果一个数列,全是负数,那么最大子列就是最大的那个负数;如-5 -7 -6 -3 -8 最大子列为-3

那么将该子列 -5 -7 -6 -3 -8与正子列合并 -5 -7 -6 -3 -8 2 5,我们知道最大子列为2 5

那么-57 2 3 -8 9     应该舍弃-5这个子列从第一个非负数开始 7 2 3 -8 9

5 -76 3 2            要舍弃5 -7这个子列

求解方案:

将数列从左到右依个分为多个子列,例如-5 7 2 3 -8 9分为

-5 -5 7 -5 7 2 -5 7 2 3;等

子列为负子列,去除该子列,将剩余的数列依个分为多个子列

代码如下:

#include<stdio.h>  

intmain() 

    int i, j, t;

    intn, number, max, sum, start, end, tempStart; //tempStart用来更新start,max当前最大子列,sum子列和

    while(scanf("%d", &t) !=EOF){

              for (i = 1; i <= t; i++)

              {

                     max = -1005;            //初定义max=-1005 < -1000

                     sum = 0;

                     tempStart = 1;

                     scanf("%d",&n);

                     for (j = 1; j <= n; j++)

                     {

                            scanf("%d",&number);

                            sum += number;

                            if (sum > max)

                            {

                                   max = sum;       //更新最大子列

                                   start =tempStart;

                                   end = j;       

                            }

                            if (sum < 0)           //前面的子列和为负数,则重新开始一条子列

                            {

                                   sum = 0;

                                   tempStart = j+ 1;

                            }

                     }

                     printf("Case%d:\n", i);

                     printf("%d %d%d\n", max, start, end);

                     if (i < t)

                            printf("\n");

              }

       }

}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值