Loading

PAT 1007 Maximum Subsequence Sum

1007 Maximum Subsequence Sum (25分)

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 1≤i≤j≤K. 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


时间限制: 200 ms
内存限制: 64 MB
代码长度限制: 16 KB
 

思路

这题是最大连续子序列的和,是一道典型的动态规划问题。
这题的坑主要在数列全是负数和0的情况,此时应该输出0 0 0.
 
 1 #include <iostream>
 2 #include <stdio.h>
 3 
 4 using namespace std;
 5 
 6 int a[10005];
 7 int memo[10005];
 8 
 9 int main()
10 {
11     int k;
12     int flag = 0; 
13     scanf("%d", &k);
14     //下标0用作哨兵 
15     for(int i = 1; i <= k; ++i)
16     {
17         scanf("%d", &a[i]); 
18         if(a[i] >= 0)
19             flag = 1;
20         
21     }
22     
23     //全为负数 
24     if(flag == 0)
25     {
26         cout << 0 << ' ' << a[1] << ' ' << a[k];
27         return 0;
28     }
29     
30     for(int i = 1; i <= k; ++i)
31     {
32         if(a[i] + memo[i-1] < 0)
33             memo[i] = 0;
34         else
35             memo[i] = a[i] + memo[i-1];
36     }
37     
38     int maxSum = -1;
39     int index_i, index_j = -1;
40     for(int i = 1; i <= k; ++i)
41     {
42         // 这里增加一个a[i]>=0的条件,是为了处理该数列只有负数和0的情况, 
43         // 这种情况应该输出0 0 0 
44         if(maxSum < memo[i] && a[i] >= 0)
45         {
46             maxSum = memo[i];
47             index_j = i;
48         }
49     }
50 
51     int j = index_j;
52     // 因为下标从1开始,所以j>=1 
53     while(j >= 1 && memo[j] >= 0)
54     {
55         //memo[j]等于0的时候a[j]可以为0 
56         if(memo[j] == 0 && a[j] < 0)
57             break;
58         --j;
59     }
60 
61     
62     index_i = j + 1;
63     
64     cout << maxSum << ' ' << a[index_i] << ' ' << a[index_j];
65     
66 
67     return 0;
68 }

 

posted @ 2020-03-26 22:00  拾月凄辰  阅读(150)  评论(0编辑  收藏  举报