Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 156188 Accepted Submission(s): 36520
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
题意:给一列数,找出其中连续和最大的一段子序列,输出最大连续和以及对应连续子序列的起点位置和终点位置。
解析:本题可用贪心,也可用dp处理。下面介绍的是贪心版本:
开一个变量max_sum来记录连续子序列和的最大值,用begin记录max_sum对应序列的起点位置,用end记录max_sum对应序列的终点位置,用sum记录当前序列的连续和,pos记录当前sum的起点位置。每次都将依次将一个数a[j]加到sum里去,如果sum < a[j], 那就代表不加a[j]之前的sum < 0,这样的话,我们就把前一段的舍掉,更新pos = j,sum = a[j],让新的一段子序列从位置j开始,如果这个时候的 sum > max_sum,那么我们就更新max_sum,同时也应该更新max_sum所对应的起点和终点位置。重复上述操作,直到把所有的序列全部加到sum。这时候的max_sum,begin,end即为所求。详见代码
AC代码:
#include<stdio.h> int main() { int n; int a[100005]; int t; int k=1; scanf("%d",&t); while(t--) { scanf("%d",&n); for(int i=0; i<n; i++) scanf("%d",&a[i]); int sum,max_sum,begin,end,pos; sum=max_sum=a[0]; //初始化 begin=end=pos=0; for(int j=1; j<n; j++) //循环n-1次,把剩下的n-1个数全部处理,因为第一个数已经放到sum里了 { sum+=a[j]; //把a[j]加到sum里 if(sum<a[j]) //没加a[j]之前的sum < 0,更新sum和pos { pos=j; sum=a[j]; } if(sum>max_sum) //更新max_sum,begin和end { max_sum=sum; end=j; begin=pos; } } printf("Case %d:\n",k++); printf("%d %d %d\n",max_sum,begin+1,end+1); //输出结果 if(t) printf("\n"); } return 0; }