HDU 1003(A - 最大子段和)
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]
代码:
1 #include<cstdio> 2 #include<iostream> 3 using namespace std; 4 const int maxn=100005; 5 6 int a[maxn],b[maxn],c[maxn];//b表示最大子段和,c表示开始的位置 7 8 int main() 9 { 10 int t,m=1; 11 scanf("%d",&t); 12 while(t--) 13 { 14 int n; 15 scanf("%d",&n); 16 for(int i=1;i<=n;i++) 17 scanf("%d",&a[i]); 18 b[1]=a[1];//记开始时的子段和为b[1] 19 c[1]=1;//开始时的位置为1 20 for(int i=2;i<=n;i++) 21 { 22 if(b[i-1]>=0) 23 { 24 b[i]=b[i-1]+a[i];//子段和 25 c[i]=c[i-1]; 26 } 27 else 28 { 29 b[i]=a[i]; 30 c[i]=i; 31 } 32 } 33 int max=b[1];//令起始位置最大值为b[1] 34 int end=1; 35 for(int i=2;i<=n;i++) 36 { 37 if(b[i]>max) 38 { 39 max=b[i]; 40 end=i;//结束位置 41 } 42 } 43 printf("Case %d:\n",m++); 44 printf("%d %d %d\n",max,c[end],end); 45 if(t) 46 printf("\n"); 47 } 48 return 0; 49 }
我先在杭电上做了几遍,提交一直都是WA,改了几次都是WA。第一次是因为我直接把开始位置写为1,根本没有计算c[i]。后来又出现了PE,因为我没有写if(t)。改了几次终于改成功了。