PAT甲级 1007 Maximum Subsequence Sum (25 分)

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

解题思路

下面的这个解释非常好,十分利于理解。现分享给大家。

(作者:CodeLike  来源:CSDN  原文:https://blog.csdn.net/CV_Jason/article/details/80910763 
版权声明:本文为博主原创文章,转载请附上博文链接!)
  这是一道动态规划(dynamic programming,DP)的题目。考虑,在输入的时候就开始进行累加,设置一个总和sum,上下标low_index和high_index,以及用于每一次输入新元素时,进行试探的temp计算临时总和,以及临时上下标,temp_low_index和循环控制变量i,在输入的同时,进行累加,逻辑如下: 
  如果总和一直在增加,则认为这个序列符合要求的,记录临时总和和临时上下标,并更新到总和和上下标; 
  如果新增元素使得总和减小,那么不更新上下标,只记录临时总和,期待下一个更大的值; 
  如果新增数据使得总和为负,显然,那么这个新的元素明显会拉低前面所有总和,需要重新探测,那么使临时总和赋值零,临时上下标设置为当前值,以重新记录。总和和上下标保持上一次记录。 
  最后循环遍历所有的输入元素之后,就能得到最大总和序列,但是要注意特殊情况,如果总和是负的,即整个序列都没有正值,需要输出零。 
  对每个输入元素进行探测,是一个子过程,每一个子过程都判断是否能得到符合要求的序列,得到最优解,这是一种动态规划的思想。 

#include
#include
#include
using namespace std;
int main(){
  int n;
  scanf("%d", &n);
  vector v(n);
  int rindex=n-1,lindex=0,lindexTmp;
  int sum=-1;
  int temp=0;
  for(int i=0;i>v[i];
    temp+=v[i];
    
    if(temp<0){
      temp=0;
      lindexTmp=i+1;
    }
    else if(temp>sum){
      sum=temp;
      lindex=lindexTmp;
      rindex=i;
    }
  }
  if(sum<0){
    sum=0;
  }
  cout<

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(PAT)