最大子列拓展----输出最大子列的右边坐标与左边坐标
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
题意:与之前的题类似,输出最大子列和,以及左边坐标和右边坐标。如果最大子列和小于0的话输出0和两端的值,如果最大子列和等于0的话输出0 0 0
题解:总结四种算法,害死在线处理比较方便,与是采用在线处理的方法做此题,下面考虑问题为如何寻找左端和右端,右端好找,如果sum大于maxn将i定义为right即可。
左端的话只能进行从右端到左边扫描,如果sum==maxn,left即为i注意此处不能写break,毕竟可能出现前面几个加起来等于0的情况
然后再考虑特殊情况,第一个是最大子列和全为负数,即sum的max小于0,此时扫描的时候sum应该小于0,所以输出即可
麻烦的是有0也有负数,思路是判断子列中的最大值,如果最大值==0的话输出0 0 0,否则输出0 shu[0] shu[T-1]
代码:
#include<iostream>
#include<algorithm>
using namespace std;
int shu[100100];
int main()
{
int sum=0,maxn=0,T,maxx=-0x3f3f3f3f3f;
cin>>T;
int left=0,right=T-1;
for(int i=0;i<T;i++)
cin>>shu[i];
for(int i=0;i<T;i++)
{
sum+=shu[i];
maxx=max(maxx,shu[i]);
if(sum>maxn)
{
maxn=sum;
right=i;
}
if(sum<0) sum=0;
}
sum=0;
for(int i=right;i>=0;i--)
{
sum+=shu[i];
if(maxn==sum) left=i;
}
if(maxn>0) cout<<maxn<<" "<<shu[left]<<" "<<shu[right]<<endl;
else if(sum==0||maxx==0) cout<<0<<" "<<0<<" "<<0<<endl;
else if(sum<0) cout<<0<<" "<<shu[0]<<" "<<shu[T-1]<<endl;
return 0;
}
浙公网安备 33010602011771号