max sum

A - 最大子段和
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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

程序分析:此题的基本思路是这样的。给你一串数,关键是选出其中和最大的连续的一串。可以这样想,首先选定第一个数,再与第二个数相比较,如果两都相加比第一个数小,就可以从第二个开始计算,如果相加结果变大,则还是从第一个相比较。之后再将每一个和与最大的和max相比较,大则交换,不大于则不变:

程序代码:

#include<stdio.h>  
int main()
{  
    int n,i,j,k,nums,a[100001],sum,b,start,end,start1,end1;  
    scanf("%d",&n);   
    for(i=1;i<=n;i++)
    {   
        scanf("%d",&nums);  
        for(j=1;j<=nums;j++)
        {              
            scanf("%d",&a[j]);  
        }  
        sum=a[1]; b=-1001; start=end=0;   
        for(k=1;k<=nums;k++)
        {      
            if(b>=0) 
            {        
                b+=a[k];    
                end++;       
       }         
            else
            {        
                b=a[k];  
                start=end=k;  
            }            
            if(b>=sum)
            {           
                sum=b;    
                start1=start;   
                end1=end;       
       }         
 }         
        printf("Case %d:
",i);        
        printf("%d %d %d
",sum,start1,end1);      
        if(i<n)printf("
");   
    }  
    return 0;  }
原文地址:https://www.cnblogs.com/yilihua/p/4721385.html