HDU_oj_1003 Max Sum
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
分析:
此题为连续子序列求最大和问题,主要思路有①枚举②累积遍历③动态规划④分治
方法比较多,将会持续更新所有算法
注意点:
①每种case中间的空行
②注意算法复杂度,枚举肯定行不通
可以阅读以下博文,详细了解各种解法:
https://www.cnblogs.com/TWS-YIFEI/p/5590532.html
http://blog.csdn.net/hcbbt/article/details/10454947
1 //累积遍历算法 2 /* 3 算法复杂度 O(n) 4 5 */ 6 7 #include<iostream> 8 #define MAX 100100 9 10 int main() 11 { 12 int num[MAX+2]={0}; 13 int t,n; 14 int sum,max; 15 int m,kk,ll; 16 17 scanf("%d",&t); 18 for(int i=1;i<=t;i++) 19 { 20 scanf("%d",&n); 21 scanf("%d",&num[0]); 22 sum=max=num[0]; 23 m=kk=ll=0; 24 25 for(int j=1;j<n;j++) 26 { 27 scanf("%d",&num[j]); 28 29 if(sum<0) 30 { 31 sum=num[j]; 32 m=j; 33 } 34 else 35 sum+=num[j]; 36 37 if(sum>max) 38 { 39 max=sum; 40 kk=m; 41 ll=j; 42 } 43 } 44 if(i!=1) 45 printf("\n"); 46 printf("Case %d:\n",i); 47 printf("%d %d %d\n",max,kk+1,ll+1); 48 } 49 return 0; 50 }