您的位置:首页 > 编程语言 > C语言/C++

最大连续子序列

2015-07-16 23:30 411 查看
E - 最大连续子序列

Description

给定K个整数的序列{ N1, N2, …, NK },其任意连续子序列可表示为{ Ni, Ni+1, …,

Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个,

例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和

为20。

在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该

子序列的第一个和最后一个元素。

Input

测试输入包含若干测试用例,每个测试用例占2行,第1行给出正整数K( < 10000 ),第2行给出K个整数,中间用空格分隔。当K为0时,输入结束,该用例不被处理。

Output

对每个测试用例,在1行里输出最大和、最大连续子序列的第一个和最后一个元

素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。

Sample Input

6

-2 11 -4 13 -5 -2

10

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

6

5 -8 3 2 5 0

1

10

3

-1 -5 -2

3

-1 0 -2

0

Sample Output

20 11 13

10 1 4

10 3 5

10 10 10

0 -1 -2

0 0 0

AC代码:

AC代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
int a[10001];
int n,i,j,x,y,ma,sum;
bool flag=true;
while(scanf("%d",&n)&&n)
{
flag=true;
for(i=0;i<n;++i)
{
scanf("%d",&a[i]);
if(a[i]>0)flag=false;
}
x=j=a[0];y=a[0];sum=0;ma=a[0];
for(i=0;i<n;++i)
{
if(sum>=0)
{
sum+=a[i];
if(ma<sum)
{ma=sum;y=a[i];x=j;}

}
else
{
j=a[i];
sum=j;
}
if(flag&&a[i]==0)//因为一开始赋值了a【0】,所以要添加特判
{
ma=0;
}
}
if(ma<0)
printf("0 %d %d\n",a[0],a[n-1]);
else if(flag&&ma==0)//当所有数都为负数且有一个是0的话只有这种情况
printf("0 0 0\n");
else
printf("%d %d %d\n",ma,x,y);
}
return 0;
}


这段代码看得我浑身发抖,太厉害。。。

大神代码:

#include "iostream"
#include "stdio.h"
#include "math.h"
#include "vector"
#include "queue"
#include "memory.h"
#include "algorithm"
#include "string"
using namespace std;
#define max(a,b) a>b?a:b
#define min(a,b) a<b?a:b

int n;
int a[10010];

int main()
{
while(scanf("%d",&n)!=EOF&&n)
{
int i,j=0,tmp=0,sum=0,maxx=-1,s=0,e=n-1;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
tmp+=a[i];
if(tmp>maxx)
{
s=j;
e=i;
maxx=tmp;
}
else if(tmp<0)
{
j=i+1;
tmp=0;
}
}
if(maxx<0)
maxx=0;
printf("%d %d %d\n",maxx,a[s],a[e]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++