PAT 1007 Maximum Subsequence Sum (25 分) (最大连续子序列和)

一、题目描述

Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A continuous subsequence is defined to be { N​i​​, N​i+1​​, ..., N​j​​ } 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

四、思路

对于任意一个位置来说,如果前一位置的子序列和小于零,则以该位置为起点重新开始,否则加在前一个子序列的末尾。

状态转移方程为 dp[i] = max(A[i],dp[i-1]+A[i]),题目需要记录子序列的开头和结尾的数,将dp设为结构体,包含当前值和序列开头序号即可。

#include<iostream>
using namespace std;
int n,A[10010];
struct seq{
	int first,value;
}dp[10010];
int main(){
	scanf("%d",&n);
	for(int i = 0;i<n;i++){
		scanf("%d",&A[i]);
	}
	dp[0].first = 0;
	dp[0].value = A[0];
	for(int i = 1;i<n;i++){
		if(dp[i-1].value<0){
			dp[i].first = i;
			dp[i].value = A[i];
		}else{
			dp[i].first = dp[i-1].first;
			dp[i].value = dp[i-1].value + A[i];
		}
	}
	int k = 0;
	for(int i = 1;i<n;i++){
		if(dp[i].value > dp[k].value){
			k = i;
		}
	}
	if(dp[k].value < 0){
		printf("0 %d %d\n",A[0],A[n-1]);
	}else{
		printf("%d %d %d\n",dp[k].value,A[dp[k].first],A[k]);
	}
	return 0;
}

 


版权声明:本文为weixin_43347688原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。