Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 183319 Accepted Submission(s): 42766
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
动态规划问题,给你一个数组,让你求从一个从i到j和最大的这么一个范围,策略是:每输入第i个数要去判断要不要把这个数加入我前面所组成的数组x[i-1]里, 如果加入这个数后得到和不小于这个数,那就把这个数加入前面的数列,否则重新开始构建最大和的数列。 用两个数组x[i]存max(x[i]+a,a),x1[i]存处理每一个数时开始的位置 例子:输入 5 6 -1 5 4 7时
6 | -1 | 5 | 4 | -7 | |
x | 6 | 5 | 10 | 14 | 7 |
x1 | 1 | 1 | 1 | 1 | 1 |
循环一遍找出最大的和为14,开始的位置为1,结束位置为4(第4个数) 例子输入 8 0 6 -7 1 6 1 -5 9 (自己造的例子)
0 | 6 | -7 | 1 | 6 | 1 | -5 | 9 | |
x | 0 | 6 | -1 | 1 | 7 | 8 | 3 | 12 |
x1 | 1 | 1 | 1 | 4 | 4 | 4 | 4 | 4 |
(输入第4个数的时候(-1+1=0<1)所以重新从第四个数开始) 循环一遍找出最大的和为12,开始的位置为4,结束位置为8(第8个数)
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int INF=0x3f3f3f3f;
int main()
{
int T;
int x[100005];
int x1[100005];
int cas=1;
scanf("%d",&T);
while(T--)
{
memset(x,0,sizeof(x));
memset(x1,0,sizeof(x1));
//memset(x2,0,sizeof(x2));
int a,b=-INF,n;
scanf("%d",&n);
x[0]=-INF;
x1[0]=1;
for(int i=1;i<=n;i++)
{
scanf("%d",&a);
if(x[i-1]+a>=a)
{
x[i]=x[i-1]+a;
x1[i]=x1[i-1];
}
//x[i]=max(x[i-1]+a,a);
else
{
x[i]=a;
x1[i]=i;
}
}
int s,e;
for(int i=1;i<=n;i++)
{
if(x[i]>b)
{
b=x[i];
s=x1[i];
e=i;
}
}
printf("Case %d:\n",cas++);
printf("%d %d %d\n",b,s,e);
if(T!=0)printf("\n");
}
}