您的位置:首页 > 其它

暑期-dp46道(2)

2016-07-15 19:59 169 查看
杭电oj1231最大连续子序列题解


最大连续子序列

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)


Problem 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

HintHint
Huge input, scanf is recommended.

和dp专题系列(1)基本没差,就是加了个全为负数时的情况,判断下就好了;

PS:改下输出格式A

代码:

#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<iostream>
#include<stack>
#include<queue>
#include<limits>
using namespace std;
#define debug 0
const int maxn=100000+5;
int data[maxn],ans[maxn],numberNum,maxSum,startPos,endPos;
bool judge()
{
for(int i=1;i<=numberNum;i++)
{
if(data[i]>=0)
{
return false;
}
}
return true;
}
void Do()
{
int j;
if(judge())
{
printf("0 %d %d\n",data[1],data[numberNum]);
}
else{
for(int i=1; i<=numberNum; i++)
{
if(ans[i]>maxSum)
{
maxSum=ans[i];
startPos=endPos=i;
}
}
for(j=endPos-1; ans[j]>=0&&j>0; j--);
startPos=j+1;
printf("%d %d %d\n",maxSum,data[startPos],data[endPos]);
}
}
int main()
{
#if debug
freopen("in.txt","r",stdin);
#endif // debug
while(~scanf("%d",&numberNum))
{
if(numberNum==0)
break;
maxSum=INT_MIN;
memset(data,0,sizeof(data));
for(int i=1; i<=numberNum; i++)
{
scanf("%d",&data[i]);
ans[i]=data[i];
if(ans[i-1]>0)
ans[i]+=ans[i-1];
}
Do();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: