1007 Maximum Subsequence Sum (25分)
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.
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.
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.
10
-10 1 2 3 4 -5 -23 3 7 -21
10 1 4
题意:给k个数字输出他的最大子段和以及字段和的开始元素结束元素,若所有元素都是复数(即最大字段和是负的),则和为0,并输出数组的第一个元素和最后一个元素;若最大字段和不唯一就输出开始下标较小的那一组。
转移方程:dp[i]=max(a[i],dp[i−1]+a[i]) 选取单个元素和取和 中较大的一个
#include
#include
#include
using namespace std;
int main(){
int n,maxn=0;
cin>>n;
vector v(n),dp(n);
for(int i=0;i=0;i--){
sum+=v[i];
if(sum==maxn)
left=i;
}
if(maxn<0) printf("0 %d %d\n",v[0],v[n-1]);
else printf("%d %d %d\n",maxn,v[left],v[right]);
return 0;
}
另参考柳神:https://blog.csdn.net/liuchuo/article/details/52144554
#include
#include
using namespace std;
int main()
{
int k;
cin>>k;
int temp=0,l=0,r=k-1,sum=-1,templeft=0;
vector v(k);
for(int i=0;i>v[i];
temp+=v[i];
if(temp<0){
temp=0;
templeft=i+1;
}
else if(temp>sum){
sum=temp;
l=templeft;
r=i;
}
}
if(sum<0) sum=0;
cout<