Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 137277 Accepted Submission(s): 31816
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
题目很长意思是给你一个一些数,你需要找出他们最大的一个连续子序列和,并且还要找出最大连续子序列和的开始和结束的位置;
题目分析
首先我们需要两个数组第一个a[i]用来储存原始数据,第二个数组sum[i]用来更新这个值sum[i]=max(sum[i-1]+a[i],a[i])当把整个原始数据遍历一遍后也就可以找到最大的值了,当我们找到最大的值时用一个变量来储存在这个最大值时候的i的数据这就是最大连续和的结束位置,然后在从结束位置开始往回遍历一遍就能找到开始的位置
下面直接上代码吧
#include<stdio.h>
#include<limits.h>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string.h>
using namespace std;
int main(void)
{
int n,m,z=0;
int a[100001];
int sum[100001];
cin>>n;
while(n--)
{
int max0=INT_MIN;
int begin=1,end=1;
int sum1=0;
cin>>m;
for(int i=1;i<=m;i++)
{
cin>>a[i];
sum[i]=max(sum[i-1]+a[i],a[i]);
if(max0<sum[i])
{
max0=sum[i];
end=i;
}
}
for(int i=end;i>=1;i--)
{
sum1+=a[i];
if(sum1==max0)
{
begin=i;
break;
}
}
z++;
cout<<"Case "<<z<<":"<<endl;
cout<<max0<<" "<<begin<<" "<<end<<endl;
if(n)
{
cout<<endl;
}
}
}