Max Sum
来源:互联网 发布:caffe axis 编辑:程序博客网 时间:2024/05/16 07:31
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 119431 Accepted Submission(s): 27647
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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
Sample Output
Case 1:14 1 4Case 2:7 1 6
思路 : 用for循环累加 如果和小于0 就清零 然后再改变first last
#include <iostream>
#include <stdio.h>
using namespace std;
int main ()
{ int a[100050],i,j,sum1,temp,first,last,t,n,max1;
scanf("%d",&t);
for(j=1;j<=t;j++)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sum1=0,temp=0,last=0,max1=-1001;
for(i=0;i<n;i++)
{
sum1+=a[i];
if(sum1>max1)
{
max1=sum1;
first=temp;
last=i;
}
if(sum1<0)
{
sum1=0;
temp=i+1;
}
}
printf("Case %d:\n%d %d %d\n",j,max1,first+1,last+1);
if(j!=t)
printf("\n");
}
return 0;
}
#include <stdio.h>
using namespace std;
int main ()
{ int a[100050],i,j,sum1,temp,first,last,t,n,max1;
scanf("%d",&t);
for(j=1;j<=t;j++)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sum1=0,temp=0,last=0,max1=-1001;
for(i=0;i<n;i++)
{
sum1+=a[i];
if(sum1>max1)
{
max1=sum1;
first=temp;
last=i;
}
if(sum1<0)
{
sum1=0;
temp=i+1;
}
}
printf("Case %d:\n%d %d %d\n",j,max1,first+1,last+1);
if(j!=t)
printf("\n");
}
return 0;
}
- Max Sum
- Max Sum
- Max Sum
- max sum
- Max Sum
- Max Sum
- MAX SUM
- Max Sum
- Max Sum
- max sum
- Max Sum
- Max sum
- Max Sum
- Max sum
- Max Sum
- Max Sum
- Max Sum
- max sum
- IOS应用内购买(In App Purchase)总结
- 修改ubuntu tweak 爱壁纸默认下载目录
- sem_wait
- 我的第一天
- 建立web service client
- Max Sum
- Single Number
- 『Game』lua和c/c++互相调用实例分析
- 数据挖掘十大经典算法(7) AdaBoost
- vs2010调用matlab2011;
- CPSR_c是什么
- Java -- Swing 组件使用
- 设计模式:外观模式(7.2)C++版
- ios block一定会范的几个错误