PAT甲级 1007.Maximum Subsequence Sum(25) 题目翻译与答案

题目来源自PAT网站  https://www.patest.cn/

题目描述:

1007. Maximum Subsequence Sum (25)

Given a sequence ofK integers { N1, N2, ..., NK }. A continuous subsequence is definedto be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which hasthe 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 being20.

Now you aresupposed to find the largest sum, together with the first and the last numbersof the maximum subsequence.

InputSpecification:

Each input filecontains one test case. Each case occupies two lines. The first line contains apositive integer K (<= 10000). The second line contains K numbers, separatedby a space.

OutputSpecification:

For each test case,output in one line the largest sum, together with the first and the lastnumbers 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 maximumsubsequence is not unique, output the one with the smallest indices i and j (asshown by the sample case). If all the K numbers are negative, then its maximumsum is defined to be 0, and you are supposed to output the first and the lastnumbers of the whole sequence.

Sample Input:

10

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

Sample Output:

10 1 4

时间限制

400 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

题目翻译:

1007.最大的子序列和

有一个包含K个整数{ N1, N2, ..., NK }的序列。一个连续的子序列被定义为 { Ni, Ni+1, ..., Nj } (1<= i <= j <= K)。最大的子序列是指在连续的子序列中元素和最大的那个。例如,一个序列{ -2, 11, -4, 13, -5, -2 },它的最大子序列是{ 11, -4, 13 },最大和为20。

现在你需要找出最大和,以及最大子序列的第一个和最后一个序号。

 

输入说明:

每个输入文件包含一个测试实例。每个实例包含两行。第一行包含一个正整数K (<= 10000)。

第二行包含K个数,用空格分隔开。

 

输出说明:

对于每个测试实例,在一行中输出最大和,同时输出最大子序列的第一个和最后一个序号。数字必须用一个空格分隔开,但是在一行末尾不能有多余的空格。如果最大子序列不是唯一的,则输出最小的指数i和j(像样例中那样)。如果K个数都是负的,则最大和被定义为0,你应该输出整个序列的第一个和最后一个数。

 

答案代码:

#include<cstdio>
int Se[10000];
long sumT[10000]={0};
int main()
{
	int i,j,K;
	int st,sti,stj;
	long sum=-1;
	scanf("%d",&K);
	for(i=0;i<K;++i)
		scanf("%d",&Se[i]);
	for(i=0;i<K;++i)
	{
		if(i==0)
			sumT[0]=Se[0];
		else
			sumT[i]=sumT[i-1]+Se[i];
	}
	for(i=0;i<K;++i)
		for(j=i;j<K;++j)
		{
			if(i==0)
			{
			
				if(sum<sumT[j])
				{
					sum=sumT[j];
					sti=0;
					stj=j;
				}
			}
			else
			{
				if(sum<sumT[j]-sumT[i-1])
				{
					sum=sumT[j]-sumT[i-1];
					sti=i;
					stj=j;
				}
			}
		}
	if(sum<0)
		printf("%d %d %d\n",0,Se[0],Se[K-1]);
	else
		printf("%ld %d %d\n",sum,Se[sti],Se[stj]);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值