最大连续子序列
Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个,
例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和
为20。
在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该
子序列的第一个和最后一个元素。
素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。
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
20 11 13 10 1 4 10 3 5 10 10 10 0 -1 -2 0 0 0
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1231
解题思路:线性dp,sum动态记录前最大连续子序列和,这题要求sum为负数时输出0,因此sum可初始化为-1。
代码如下:
#include <cstdio>
#include <cstring>
const int maxn=10004;
int a[maxn],dp[maxn];
int main()
{
int n,i;
while(scanf("%d",&n)!=EOF&&n)
{
int sum=-1,cur=0,p=0,q=0,dex=0;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
cur+=a[i];
if(sum<cur)
{
sum=cur;
p=dex; //记录左下标
q=i; //更新右下标
}
if(cur<0) //cur为负时与之相加的和必定不是最大的,因此赋为0,从下一个数开始找
{
cur=0;
dex=i+1; //dex记录更新后的左下标,保证p值不会为n
}
}
if(sum<0)
printf("0 %d %d\n",a[0],a[n-1]);
else
printf("%d %d %d\n",sum,a[p],a[q]);
}
return 0;
}
5818


&spm=1001.2101.3001.11974&articleId=44851431&d=1&t=3&u=a85a065eace34e0bb81e695c4c88b914)

被折叠的 条评论
为什么被折叠?



