01-复杂度2 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.
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
个人分析:前一题的进阶版!(好的,我的大刀已经饥渴难耐了!!)重复的要求不赘述。特别需要注意的有三点:
1.除了需要输出最大子列和,还需要输出最大子列的头元素/尾元素。
2.输出的三个数之间要空格隔开,但是末尾又不允许有空格。
3.存在多个最大子列的情况,此时输出子列头/尾元素下标最小的那个子列。
Ojbk,话不多说,上代码:
#include<stdio.h>
void MaxSubseqSum4(int A[], int N)
{
int ThisSum, MaxSum;
int i,top,Top,End; //就像ThisSum/MaxSum的关系一样,top记录当前子列的头元素,Top记录当前最大子列的头元素
ThisSum=0;MaxSum=A[0]; //由于在线处理一个个读入元素,尾元素即为当前读入元素,可不用end另计
top=End=Top=0;
for(i=0;i<N;i++)
{
ThisSum+=A[i];
if(ThisSum>MaxSum)
{
MaxSum=ThisSum;
Top=top; //每当更新最大子列和的时候,同步更新最大子列的头元素/尾元素
End=i;
}
else if(ThisSum<0)
{
ThisSum=0;
top=i+1; //由于当前序列被舍弃,从下一元素重新开始寻找子列,头元素跟着更新
}
else if(ThisSum==MaxSum) //对应注意点3,多个最大子列的情况
{
if(top<Top) //选择头元素下标小的最大子列
{
Top=top;
End=i;
}
}
}
if(MaxSum<0)
{
Top=0;
End=N-1;
MaxSum=0;
}
printf("%d %d %d",MaxSum,A[Top],A[End]);
}
int main()
{
int A[100000]={0};int num;
scanf("%d",&num);
for(int i=0;i<num;i++)
{
scanf("%d",&A[i]);
}
MaxSubseqSum4(A, num);
return 0;
}
提交结果:
总结:菜鸡很开心呀,陈姥姥说这是PAT2004年的真题,突然就有自信继续学了有木有!!(虽然用了2个小时才改好)。总的来说,这题不难,特别是我们已经知道了在线处理算法,其他都是些细节的处理。再接再厉!