最大连续子序列
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 57 Accepted Submission(s) : 36
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Input
测试输入包含若干测试用例,每个测试用例占2行,第1行给出正整数K( < 10000 ),第2行给出K个整数,中间用空格分隔。当K为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最大和、最大连续子序列的第一个和最后一个元
素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。
素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号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
Hint
Hint
Huge input, scanf is recommended.
Huge input, scanf is recommended.
Source
浙大计算机研究生复试上机考试-2005年
#include <bits/stdc++.h>
using namespace std;
int a[10005];
int main()
{
int n;
while(~scanf("%d",&n))
{
if(n==0) break;
int t=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]>=0) t=1;
}
if(t==0) printf("0 %d %d\n",a[1],a[n]);
else
{
int pre=0,cur=0,lss=0,s=0,e=0;
for(int i=1;i<=n;i++)
{
if(a[i]>0&&pre<=0) lss=a[i];//当前和<=0,a[i]>0 ,临时起点为a[i]
if(pre+a[i]>0) pre+=a[i];//当前和+a[i]>0.当前和更新
else pre=0; //当前和+a[i]<=0 ,当前和变为0
if(pre>cur) //当前和大于实际和,更新
{
cur=pre;
s=lss;
e=a[i];
}
}
printf("%d %d %d\n",cur,s,e);
}
}
return 0;
}