HDU 1003 Max Sum

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 65556    Accepted Submission(s): 14974


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
 
 
 
 
 
 
 
 
 
 
原理:连续子串<a[i].....a[j]>的和如果< 0,那么下一个可能的最大的连续子串必定从刚才的串末尾的下一个元素开始即a[i + 1]
 
 
 
View Code
 1 #include<stdio.h>//first,end分别存最大子串的首尾。sum存连续字串(最大连续串[可能]在其中)。max_sum存最大连续和,probalbe存可能的最大连续和的首
2 int main()
3 {
4 int t,times = 1,n,i,first,end,sum,max_sum,probable,a;
5 scanf("%d",&t);
6 while( t--)
7 {
8 scanf("%d",&n);
9 sum = 0;
10 max_sum = -200000;
11 probable = 1;//不是first = 1,现在只是可能,到下面发现比目前大的连续子串时才用first记录
12 for(i = 1;i <= n;i++)
13 {
14 scanf("%d",&a);
15 sum += a;
16 if (max_sum < sum)//发现比目前大的连续子串。
17 {
18 max_sum = sum;
19 first = probable;//记录
20 end = i;//记录
21 }
22 if (sum < 0)//根据原理,后面可能有比他还大的
23 {
24 sum = 0;//重新记录
25 probable = i + 1;//可能更大的串一定从下一个开始。
26 }
27 }
28 if (times != 1)
29 {
30 printf("\n");
31 }
32 printf("Case %d:\n%d %d %d\n",times,max_sum,first,end);
33 times++;
34 }
35 return 0;
36 }
原文地址:https://www.cnblogs.com/qiufeihai/p/2319949.html