码迷,mamicode.com
首页 > 其他好文 > 详细

最大子列和CT 01-复杂度2 Maximum Subsequence Sum

时间:2015-09-29 18:36:52      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Given a sequence of K integers { N?1??, N?2??, ..., N?K?? }. A continuous subsequence is defined to be { N?i??, N?i+1??, ..., N?j?? } where 1ijK. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10
-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4

 1 #include <stdio.h>
 2 int MaxSubSum(int a[],int n);
 3 int FirstI,EndI;
 4 int main()
 5 {
 6     int n,a[10005],MaxSum;
 7     while(scanf("%d",&n)!=EOF)
 8     {
 9         for(int i = 0;i < n;i++)
10         scanf("%d",&a[i]);
11         MaxSum = MaxSubSum(a,n);
12         if(MaxSum != -1)
13             printf("%d %d %d\n",MaxSum,a[FirstI],a[EndI]);    
14         else
15             printf("0 %d %d\n",a[FirstI],a[EndI]);    
16     }
17     return 0;
18 }
19 int MaxSubSum(int a[],int n)
20 {
21     int ThisSum = 0,MaxSum= -1;
22     int firsti=-1;
23     FirstI = 0;EndI = n-1;
24     for(int i = 0;i < n;i++){
25         ThisSum += a[i];
26         if(MaxSum < ThisSum){
27             MaxSum = ThisSum;
28             EndI = i;
29             FirstI = firsti + 1;
30         }
31         else if(ThisSum < 0)
32         {
33             ThisSum = 0;
34             firsti = i;
35         }
36     }
37     return MaxSum;
38 }

 

 

最大子列和CT 01-复杂度2 Maximum Subsequence Sum

标签:

原文地址:http://www.cnblogs.com/kuotian/p/4846728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!