Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 211310    Accepted Submission(s): 49611


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
 
解题心得:
  这个题是一个简单地动态规划题,题意:输入n个数,求它的最大的子序列和。 首先写出状态转移方程: sum[i]=max{sum[i-1]+a[i],a[i]}。
  s数组是记录开始位置,每当sum加上一个a[i],值小于0的时候,s取用新的值。 ans是记录结束位置,每当sum加上一个a[i],值大于等于0的时候,更新一下。
    我又在格式问题上出错了,以后要更加注意格式问题,最后一行不需要换行!
  也可以参考这个人的思路,http://blog.csdn.net/code_pang/article/details/7772200,通过枚举发现的规律。
 
最后是代码:
#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int t;
    int n;
    int a[100005];//存储序列
    int sum[100005];//存储以每个数为结尾的子序列和
    int s[100005];//存储开始位置
    int ans;//结束位置
    scanf("%d",&t);
    for(int i=1;i<=t;i++){
        scanf("%d",&n);
        for(int i1=0;i1<n;i1++){
            scanf("%d",&a[i1]);
        }
        ans=0;
        sum[0]=a[0];
        s[0]=0;
        for(int j=1;j<n;j++){
            if(sum[j-1]>=0){
                sum[j]=sum[j-1]+a[j];
                s[j]=s[j-1];
            }else{
                sum[j]=a[j];
                s[j]=j;
            }
            if(sum[ans]<sum[j])
                ans=j;
        }
        if(i<t){
            printf("Case %d:\n%d %d %d\n",i,sum[ans],s[ans]+1,ans+1);
            printf("\n");
        }else{
            printf("Case %d:\n%d %d %d\n",i,sum[ans],s[ans]+1,ans+1);
        }
    }
    return 0;
}
View Code