Max Sum

Max Sum

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 51   Accepted Submission(s) : 8

Font: Times New Roman | Verdana | Georgia

Font Size:

Problem Description

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

Author

Ignatius.L
思路:
这题用动态规矩;
先从第一位开始往后加;把最大值用max记录;
如果sum<0那说明 前面的白加,因为前面加起来是负数 你后面怎么加都会比加上负数的大
如果你把前面加起来是负数的区间也加上,那后面的最大值会变小;
6 -1 5 4 -7
6 +(-1)+5+4=14 max=14;
6 -5 -2 7;
6 +(-5)+(-2) =-1  <0;
max=7; 如果加上前面的 -1
那max=6,比实际的小;
 
#include<iostream>
using namespace std;
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=1;i<=n;i++)
        {
            int m;
            cin>>m;
            int test[100005];
            int star=1;
            int end=1;
            int max=-9999;//记录最大和
            int k=1;//记录下一个开始位置
            int sum=0;//记录star 到end 的和


            for(int q=1;q<=m;q++)
            {
                cin>>test[q];//输入数据
            
            }


            for(int j=1;j<=m;j++)
            {
                sum=sum+test[j];
                if(sum>max)
                {
                    max=sum;
                    end=j;
                    star=k;//记录当前最大值 记录相加区间的结尾
                }
                if(sum<0)
                {
                    sum=0;
                    k=j+1;
                }

            
            }
            if(i!=1) printf("\n");
            printf("Case %d:\n",i);
            printf("%d %d %d\n",max,star,end);
        
        
        
        
        
        
        
        
        }
    
    
    
    
    
    }



return 0;
}

 

 
posted @ 2013-08-14 11:17  一只蚊子  阅读(178)  评论(0)    收藏  举报