PTA数据结构 01-复杂度2 Maximum Subsequence Sum

tech2023-02-13  95

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

加粗字段为题主踩过的坑。。。

代码

#include <stdio.h> #include <stdlib.h> int MaxSubSequenceSumAlter(int array[],int N,int* FirstNum,int* LastNum) { int ThisSum=0; int MaxSum=-1;/*初始MaxSum=-1,使得出现ThisSum=0时也能标记出Last项*/ int position_first=0; int position_last=N-1; int i; int* FirstNumFlag=malloc(N*sizeof(int));/*产生新的FirstNum时,对应坐标的项被置1*/ FirstNumFlag[0]=1;/*第一项默认为1*/ for(i=1;i<N;i++){ FirstNumFlag[i]=0;/*初始化为0*/ } for(i=0;i<N;i++){ ThisSum+=array[i]; /*以下2个if顺序不能颠倒,为了判断出ThisSum=0的情况,ThisSum的更新放在ThisSum与MaxSum的比较之后*/ if(ThisSum>MaxSum){ MaxSum=ThisSum; position_last=i; } if(ThisSum<0 && i+1<N){/*注意!由于要取子列头的min值,故ThisSum=0时不用更新FirstNumFlag*/ FirstNumFlag[i+1]=1; ThisSum=0; } } if(MaxSum==-1){/*序列全负*/ *FirstNum=array[0]; *LastNum=array[N-1]; MaxSum=0; return MaxSum; } else{ /*注意下for自带;结尾,用于检索出最大子列/项的坐标,为了可以检索出项,故first初始化为last,如果自己既是头也是尾的话就可以检索出来*/ for(position_first=position_last ; FirstNumFlag[position_first]!=1 ; position_first--); *FirstNum = array[position_first]; *LastNum = array[position_last]; return MaxSum; } } int main() { int N; if(scanf("%d",&N)==1); int* array=malloc(N*sizeof(int)); int i; for(i=0;i<N;i++) if(scanf("%d",&array[i])==1); int FirstNum=array[0]; int LastNum=array[N-1]; int max=0; max=MaxSubSequenceSumAlter(array,N,&FirstNum,&LastNum);/*存疑1:&array ?*/ printf("%d",max); printf(" %d",FirstNum); printf(" %d",LastNum); return 0; }

希望对你有用~

最新回复(0)