PAT (Advanced Level) Practice 1007 Maximum Subsequence Sum (25 分) 凌宸1642

PAT (Advanced Level) Practice 1007 Maximum Subsequence Sum (25 分) 凌宸1642

题目描述:

Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+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.

译:给定一个 K 个整数的序列 { N1, N2, ..., NK }。一个连续的子序列定义为{ Ni, Ni+1, ..., N~j ~} where 1≤i≤j≤K。最大子序列是拥有最大和的连续子序列。例如,给定序列 { -2, 11, -4, 13, -5, -2 },它的最大子序列为{11 , -4 , 13} 最大连续子序列和为20。现在你应该找出最大的和,并且找出最大子序列的第一项和最后一项。


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.

译:每个测试文件包含一个测试用例,每个测试包含两行,第一行包含一个正整数 K (≤10000)。第二行包含 K 个用空格隔开的数字。

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..

译:对于每个测试用例,在一行中输出最大和,和最大子序列的第一项和最后一项。数字必须用空格隔开,并且行末没有多与的空格。可能最大子序列不唯一,输出索引值i 和 j 最小的。如果 K 个数都是负数,那么最大和定义为 0 并且你应该输出整个序列的第一项和最后一项。


Sample Input (样例输入):

10
-10 1 2 3 4 -5 -23 3 7 -21

Sample Output (样例输出):

10 1 4

The Idea:

动态规划求最大连续子序列的和问题,不同的是,在这里需要记录起点和终点的位置。

定义一个 二维数组 dp[MAX][2] 对于任意 i , dp[i][0] 表示 以 i 结尾的最大连续子序列和。dp[i][1] 表示起点索引值。然后记录到最大的dp[i][0] 的位置,即我们需要的答案。

The Codes:

#include<bits/stdc++.h>
using namespace std;
const int MAX = 10010 ;
vector<int> num ;
int dp[MAX][2] ;
int k , t , ans ;
int main(){
	cin >> k ;
	int cnt = 0 ;
	for(int i = 0 ; i < k ; i ++){
		cin >> t ;
		if(t >= 0) cnt ++ ; // 统计非负相个数
		num.push_back(t) ; 
	}
	if(cnt == 0) { // 如果全部是负数,按照题目要求输出
		cout << 0 << " "<< num[0] << " "<< num[k-1] <<endl;
		return 0 ;
	}
	dp[0][0] = num[0] ; // 初始化 dp[0][0] 和 dp[0][1]
	ans = dp[0][1] = 0 ; // ans 记录最大的连续子序列和的结尾索引
	for(int i = 1 ; i < k ; i ++){ // 状态转移方程
		if(dp[i-1][0] + num[i] > num[i]){ 
			dp[i][0] = dp[i-1][0] + num[i] ;
			dp[i][1] = dp[i-1][1] ;
		}else{
			dp[i][0] = num[i] ;
			dp[i][1] = i ;
		}
		ans = (dp[i][0] > dp[ans][0])? i : ans ; // 如果此次获得的dp[i][0]比之前的
	}
	cout << dp[ans][0] << " "<<num[dp[ans][1]] << " "<< num[ans] << endl ;
	return 0 ;
}

posted @ 2021-05-09 20:13  凌宸1642  阅读(55)  评论(0)    收藏  举报