Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 305395 Accepted Submission(s): 72559
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
瞎胡翻译:
求一串整数中子序列的最大和(领会精神)
输入:先输入一个数T表示之后有T串整数
输出:输出最大的和,这个子序列的起始位置,这个子序列的结束位置
思路:从每行的第二整数开始,看加上前一位的最大值有没有超过自己,如果超过了,就把自己的最大值更新成刚才的和,并且begin也和上一位的begin相同,如果没超过,那么最大值就是自己,begin是自己的位置。
#include<stdio.h>
struct p{
int num;//记录这个位置的值
int max;//记录这个位置的最大值
int begin;//记录这个序列的开始位置
};
int main()
{
int t;
scanf("%d",&t);
int count=0;
while(t--)
{
count++;
struct p a[100001];
int n;
scanf("%d",&n);
int i;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i].num);
if(i==1)
{
a[i].max=a[i].num;
a[i].begin=i;
}
else
{
if(a[i].num<=a[i].num+a[i-1].max)//如果比自己大,就证明前面不是一个负值的序列
{
a[i].max=a[i].num+a[i-1].max;
a[i].begin=a[i-1].begin;
}
else//否则就相当于放弃前面的序列
{
a[i].max=a[i].num;
a[i].begin=i;
}
}
}
int ans=1;
for(i=1;i<=n;i++)
{
if(a[i].max>a[ans].max)
ans=i;
}
if(count!=1)
{
printf("\n");
}
//注意输出格式,很可能因为这个过不去
printf("Case %d:\n%d %d %d\n",count,a[ans].max,a[ans].begin,ans);
}
}