J - Max Sum

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个数,让你求出到第n个位置时,f[n]刚好是这一串数的最大和,然后输出这个最大和,以及这一串数的起点序号与终点序号(这个序号指的是求和的数的起点个终点),最大和子串。

问题:没开始写程序前我想的问题有 什么时候跳出循环? 满足什么条件才可以往里面加?
忽视的问题 就是我以为起点总是从第一个数开始,然而并不是,起点是从第一个不为0的数开始,这里有点坑

解决:前面两个问题想了很久没想明白,然后看了别人的代码,豁然开朗,自己怎么就想不到呢。后面的那个问题到是好解决,但是你得想到这一点,要不就会坑死。。。。。。。
AC代码:

#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
int t,n,m,sum,max,s1,s,e,ans;
while(~scanf("%d",&t))
{
ans=1;
while(t--)
{
sum=0;
s1=1;
max=-10000;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&m);
sum+=m;
if(sum>max)//核心代码
{
max=sum;
s=s1;
e=i;
}
if(sum<0)/*这是个坑,一开始我就没想过这个。就是起点如果小于0的话可以不从这点开始,直到遇到一个不小于0的数以此数为起点*/
{
sum=0;
s1=i+1;
}
}
if(ans-1!=0) printf("\n");//这里也要注意,就是题目给你的换行是指两次输入完以后输出第二次的结果时才换行,否则会出现格式错误
printf("Case %d:\n",ans++);
printf("%d %d %d\n",max,s,e);
}

}
return 0;
}






posted @ 2016-08-09 10:58  踮起脚望天  阅读(137)  评论(0编辑  收藏  举报