PAT 1007 Maximum Subsequence Sum 您所在的位置:网站首页 序列的下标是什么 PAT 1007 Maximum Subsequence Sum

PAT 1007 Maximum Subsequence Sum

2023-03-17 01:26| 来源: 网络整理| 查看: 265

1007 Maximum Subsequence Sum(最大连续子序列和)

Given a sequence of K integers { N 1, N 2 , …, N K}. A continuous subsequence is defined to be { N i , Ni+1, …, Nj } 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

**题意:**找出数组中连续序列的最大和,如果有重复就输出i和j小的序列,注意输出是ai和aj,如果全是负数则输出0,首和尾。(最长连续子序列的小升级版,需要记录序列的头和尾)

思路: 1.用s[i]表示以a[i]结尾的序列是从哪个元素开始的。如果只有一个元素,是s[i]=i。如果不是,说明dp[i]和dp[i-1]是同一个起点,那么s[i]=s[i-1] 2.dp思路,如果dp[i-1]+a[i]>dp[i],则更新dp[i]=dp[i-1]+a[i],说明前i-1个元素中的序列和加上这个元素大于单独这个元素的和。否则就更新dp[i]=a[i],应该从当前元素开始了。

#include using namespace std; int a[100010]; int dp[10010],s[10010]={0}; main(){ int n; cin>>n; int flag=0; for(int i=0;i printf("0 %d %d\n",a[0],a[n-1]); return 0; } dp[0]=a[0]; for(int i=1;i dp[i]=dp[i-1]+a[i]; s[i]=s[i-1]; }else{ dp[i]=a[i]; s[i]=i; } } int k=0; for(int i=1;i k=i; } } cout


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有