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
贴两个ac代码吧,心累(第一个摘抄网上)
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=500009;
const int INF=0x3f3f3f3f;
ll a[maxn];
int main()
{
ll T,n,i,j,k;
scanf("%lld",&T);
for(k=1;k<=T;k++)
{
scanf("%lld",&n);
for(i=1;i<=n;i++)
scanf("%lld",&a[i]);
ll s=0,max1=-1e9,start=1,endd=1,t=1;
for(i=1;i<=n;i++)
{
s+=a[i];
if(max1<=s)
{
max1=s;
endd=i;
start=t;
}
if(s<0)
{
s=0;
t=i+1;
}
}
printf("Case %d:\n",k);
printf("%lld %lld %lld\n",max1,start,endd);
if(T!=k)
puts("");
}
return 0;
}
都挺好理解的,跑一遍就能搞懂,主要还是理清楚思路吧
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
int sum[100010],a[100010];
int main()
{
int t,k,x,y,flag;
scanf("%d",&t);
k=0;
while(t--)
{
k++;
memset(sum,0,sizeof(sum));
int n,max1=-1001;
int i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
{
sum[i]=max(sum[i-1]+a[i],a[i]);
if(sum[i]>max1)
{
max1=sum[i];
x=i;
}
}
flag=max1;
for(i=x;i>=1;i--)
{
max1-=a[i];
if(max1==0)
{
y=i;
break;
}
}
if(k!=1)
printf("\nCase %d:\n%d %d %d\n",k,flag,y,x);
if(k==1)
printf("Case %d:\n%d %d %d\n",k,flag,y,x);
}
return 0;
}