Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, 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
这个问题用于求最大连续子序列和,用的是动态规划,输出要求还需要定出最大子序列和的左右边界。
输入的序列为A[ i ],状态dp[ i ] 表示以A[ i ] 作为末尾的最大连续子序列之和,这样这里的 i 就是右边界。第二个要解决的问题就是状态转移方程:
边界为dp[ 0 ] = A [ 0 ]
从小到大枚举dp[ i ],并通过求出dp[i]的最大值可以求出最大连续子序列之和。最大和dp[k]求出时,其右边界就是下标k。左边界的求法:定义一个数组left_r[],存放的是右边界为k时左边界的值,以序列{-2,11,7,20,15,13}为例,当i==1时,A[i] =11,而A[i] +dp[i-1] = -2+11=9,所以要将dp[i]赋值为A[1]而非是A[1]+dp[0]。相应的,左边界更新为1,而非是0.若dp[i] = A[i]+dp[i-1],left_r[i] = left_r[i-1]
第三个要解决的问题是按题目的要求,所有值为负数时求和为0,举了个例子,当序列为{-1,0},但求出的dp[k]为-1,这里是因为max_number初始化值为0和dp[1]相同,而记录最大子序列和右边界k却没有变化。将max_number修改为-1即可。
代码如下:
// 这题的目的是求出一个序列的子序列,使得子序列的和最大
// 用暴力破解无法承受复杂度,这需要动态规划的思路
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int A[maxn],dp[maxn]; //A[i] 存放序列 dp[i]存放以A[i] 为结尾的连续序列的最大和
int left_r[maxn]={0};
int main()
{
int flag = 0;
int n,k=0; //k代表右边界
int max_number = -1;
scanf("%d",&n);
for(int i = 0;i<n;i++)
{
scanf("%d",&A[i]);
}
dp[0] = A[0];
flag =(A[0]>=0)?1:0; //如果出现大于0的数,flag就变为1
left_r[0] = 0;
for(int i = 1;i<n;i++)
{
if(A[i]>=0)
{
flag =1;
}
dp[i] = max(A[i],dp[i-1]+A[i]);
if(A[i]>dp[i-1]+A[i])
{
left_r[i] = i;
}
else
{
left_r[i] = left_r[i-1];
}
}
for(int j = 0;j<n;j++)
{
if(max_number<dp[j])
{
max_number = dp[j];
k = j;
}
}
if(flag==1)
{
printf("%d %d %d",dp[k],A[left_r[k]],A[k]);
}
else if(flag==0)
{
printf("0 %d %d",A[0],A[n-1]);
}
return 0;
}