您的位置:首页 > 产品设计 > UI/UE

1007. Maximum Subsequence Sum (25)

2018-02-10 17:40 225 查看
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
题目大意:
给定一个K个整数的序列{N1, N2,…,NK }。一个连续的子序列被定义为{Ni, Ni+1,…,Nj}其中1 <= i <= j <= k=K。最大子序列是元素之和最大的连续子序列。例如,给定序列{ -2, 11, -4, 13, -5, -2 }, 它的最大子序列是{ 11, -4, 13 },最大值为20。
现在你应该找到最大和和最大子序列的第一个数和最后一个数。
输入规格:
每个测试文件包含一个测试用例。每个案例有两行。第一行包含一个正整数K(,=10000).第二行包含K个用空格隔开的数字。
输出规范:
对于每个测试用例,在一行上输出最大的和,并且输出最大子序列的第一个数字和最后一个数字。数字之间必须用一个空格隔开,在一行的末尾不允许有多余的空格。在一个案例中最大子序列可能不唯一,那么输出的是i和j最小的索引(如样例所示)。如果K个数字都是负数,那么它的最大和就是0,你应该输出整个序列的第一个数字和最后一个数字。

代码:#include<bits/stdc++.h>
int a[10001];
int main()
{
int n,i,sum,Max,start_index,end_index,index1,index2,num=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(a[i]<0)
{
num++;
}
}
if(num==n)
{
printf("0 %d %d",a[0],a[n-1]);
}
else
{
Max=a[0];
sum=a[0];
start_index=0;
end_index=0;
index1=0;
index2=n-1;
for(i=1;i<n;i++)
{
if(sum>Max)
{
Max=sum;
index1=start_index;
index2=i-1;
}
if(sum<=0)
{
sum=a[i];
start_index=i;
}
else
{
sum+=a[i];
}
}
printf("%d %d %d",Max,a[index1],a[index2]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: