PATA 1007.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
题意:给定一个整数序列,先告知你这个序列有多少个数,然后要求你求出这个序列中最大的子序列和以及子序列的首尾元素,当有相同的最大子序列和时,输出秩最小的那个子序列,当输入全为负数时,最大子序列和定义为0,并输出整个序列的首尾元素


AC代码

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
	int k;
	cin>>k;
	int a[100005];
	for(int i=0;i<k;i++)
	{
		cin>>a[i];
	} 
	int first=a[0],last=a[0],tempfirst=a[0],templast=a[0];
	int MaxSum=a[0],ThisSum=0;
	for(int i=0;i<k;i++)//使用最优子序列求和方法(在线算法),同时使用动态的两个界桩对子序列首尾进行标记 
	{
		if(ThisSum>=0)
		{
			ThisSum+=a[i];
			templast=a[i];
		}
		else
		{
			ThisSum=a[i];
			tempfirst=a[i];
			templast=a[i];
		}
		if(ThisSum>MaxSum)//记录当前最大子序列和以及界桩,及时后序有相同的最大子序列和,界桩也不会被更新,确保输出秩最小的子序列 
		{
			MaxSum=ThisSum;
			last=templast;
			first=tempfirst;
		}
   }
    if(MaxSum<0)//处理最大子序列和为负数的情况,即全部输入均为负数 
    {
    	MaxSum=0;
    	first=a[0];
    	last=a[k-1];
	}
	cout<<MaxSum<<" "<<first<<" "<<last;
	return 0;
}
//当数据是负数和0时,first和last两个界标都会移到0处;
//选择用a[0]初始化所有变量有很多好处,比如处理只有单个数据输入时 
总结:这个求最大子序列和的在线算法很精髓,要烂熟于心,其次就是边界条件的处理要注意


猜你喜欢

转载自blog.csdn.net/qq_33657357/article/details/80299830