Max Sum
来源:互联网 发布:win10无损分区软件 编辑:程序博客网 时间:2024/05/16 07:46
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 141904 Accepted Submission(s): 33027
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
思路:用到了动态规划,理解清这一步: 当m+now<m时,就只需要从下一步开始计数。
注意:如果一般方法例如用两个for会超时。
#include<stdio.h>
int main()
{
int now,max,x,m,n,i,j,test,pos1,pos2;
scanf("%d",&test);
for(i=1; i<=test; i++)
{
scanf("%d %d",&n,&m);
max=now=m;
pos1=pos2=x=1;
for(j=2; j<=n; j++)
{
scanf("%d",&m);
if(m+now<m)
{
now=m;
x=j;
}
else now+=m;
if(now>max)
{
max=now;
pos1=x;
pos2=j;
}
}
printf("Case %d:\n%d %d %d\n",i,max,pos1,pos2);
if(i!=test)
printf("\n");
}
// while(1);
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
- Build opencv libraries for android arm, x86 ubuntu
- PKU 3122
- keyBoard添加额外的按钮
- uva 11234(二叉树、线性表)
- 1.3.2 声明式编程风格
- Max Sum
- 《Linux》天影linux系列笔记一——linux常用命令详解:echo
- Sublime Text2.0.2注册码
- _beginthreadex : undeclared identifier解决办法
- 《Linux》天影linux系列笔记一——linux常用命令详解:vi
- solve it--非线性方程求根
- 删除确认
- 组织行为学对项目管理的意义
- 《Linux》天影linux系列笔记一——linux常用命令详解:env