题目大概:
计算如下图所示的d(A)。
t1 t2
d(A) = max{ ∑ai + ∑aj | 1 <= s1 <= t1 < s2 <= t2 <= n }
i=s1 j=s2
思路:
这个题其实是求最大连续2字段和问题。
就是从前面慢慢加。就是求两段最大的不重合的字段加起来就行了。
最大子段和方法是:
a[n]是第n个数结尾的最大字段和。b[n]是第n个数。
a[1]=max(b[1],0)。
a[n]=max(a[n-1]+b[n],0)。
这个题不过复杂一点。
感想:
简单题一复杂就wrong answer好多次。
代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
int main()
{int t;
scanf("%d",&t);
for(int i=0;i<t;i++)
{int n,a[50001],dp[50001],h[50001],sum=0,mm=-10001;
scanf("%d",&n);
dp[0]=-10001;
for(int l=1;l<=n;l++)
{
scanf("%d",&a[l]);
if(dp[l-1]>a[l]+sum)dp[l]=dp[l-1];
else dp[l]=a[l]+sum;
sum+=a[l];
if(sum<0)sum=0;
}
h[n+1]=-10001;
sum=0;
mm=-200000;
for(int j=n;j>0;j--)
{
if(h[j+1]>a[j]+sum)h[j]=h[j+1];
else h[j]=a[j]+sum;
sum+=a[j];
if(sum<0)sum=0;
if(dp[j]+h[j+1]>mm)mm=dp[j]+h[j+1];
}
printf("%d\n",mm);
}
return 0;
}
本文介绍了一种解决最大连续2字段和问题的方法,并通过具体示例解释了如何使用动态规划来找到数组中两个不重叠子数组的最大和。文章还提供了一段C++代码实现。
523

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



