HDU 1003 MAXSUM(最大子序列和)

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
 
题目主要是求连续最大子序列的和,并输出最大子序列的左边界和右边界。
注意输出的格式为每两组数据之间输出一个空行,最后一组数据没有。
 
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <algorithm>
 5 using namespace std;
 6 #define INF 0x3f3f3f3f
 7 int main()
 8 {
 9     int t,n;
10     int i,j,k=0;
11     int Max,sum,x,y,l,d;
12     scanf("%d",&t);
13     while(t--)
14     {
15         Max=sum=-INF;
16         scanf("%d",&n);
17         for(i=1; i<=n; i++)
18         {
19             scanf("%d",&d);
20             if(sum+d<d)
21                 sum=d,l=i;
22             else
23                 sum+=d;
24             if(Max<sum)
25             {
26                 x=l;
27                 y=i;
28                 Max=sum;
29             }
30         }
31         if(k)
32             printf("
");
33         printf("Case %d:
",++k);
34         printf("%d %d %d
",Max,x,y);
35     }
36     return 0;
37 }
View Code
原文地址:https://www.cnblogs.com/cxbky/p/4730091.html