HDU 1003(A - 最大子段和)

时间:2023-12-17 08:51:26

HDU   1003(A - 最大子段和)

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=87125#problem/A

题目:

Max Sum

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
题意:
给出一个序列,求此序列的最大子段和 及开始和结束的位置。
分析:
动态规划。求最大子段和。b[i]表示最大子段和。c[i]表示子段和开始的位置。b[i]=(b[i-1]+a[i])>a[i]?b[i-1]+a[i]:a[i]
代码:
 #include<cstdio>
#include<iostream>
using namespace std;
const int maxn=; int a[maxn],b[maxn],c[maxn];//b表示最大子段和,c表示开始的位置 int main()
{
int t,m=;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(int i=;i<=n;i++)
scanf("%d",&a[i]);
b[]=a[];//记开始时的子段和为b[1]
c[]=;//开始时的位置为1
for(int i=;i<=n;i++)
{
if(b[i-]>=)
{
b[i]=b[i-]+a[i];//子段和
c[i]=c[i-];
}
else
{
b[i]=a[i];
c[i]=i;
}
}
int max=b[];//令起始位置最大值为b[1]
int end=;
for(int i=;i<=n;i++)
{
if(b[i]>max)
{
max=b[i];
end=i;//结束位置
}
}
printf("Case %d:\n",m++);
printf("%d %d %d\n",max,c[end],end);
if(t)
printf("\n");
}
return ;
}

我先在杭电上做了几遍,提交一直都是WA,改了几次都是WA。第一次是因为我直接把开始位置写为1,根本没有计算c[i]。后来又出现了PE,因为我没有写if(t)。改了几次终于改成功了。