POJ Maximum sum

本文探讨了一个利用枚举分割点方法解决给定整数序列中找到最大值子序列的问题。通过动态规划计算每个分割点的序列最大值,并使用辅助数组记录分割点前后的最大序列值。最终通过遍历所有可能的分割组合,确定最优答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
POJ Maximum sum - 深海灬孤独 - Alex
Your task is to calculate d(A).

Input

The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input. 
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, ..., an. (|ai| <= 10000).There is an empty line after each case.

Output

Print exactly one line for each test case. The line should contain the integer d(A).

Sample Input

1

10
1 -1 2 2 3 -3 4 -4 5 -5

Sample Output

13

Hint

In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer. 

Huge input,scanf is recommended.

Source

POJ Contest,Author:Mathematica@ZSU



DP题,思路是:枚举分割点,设数组dp[i]表示以元素i结束的序列中的最大值,设lm[i]为i之前的最大序列的值
同理设rm[i]为i之后的最大序列的值

#include<stdio.h>
#include<string.h>
const int maxn=50010;
//枚举分割点

int dp[maxn];
int lm[maxn];
int rm[maxn];
int str[maxn];
int max(int a,int b)
{
return a>b?a:b;
}
int main()
{
int t;
int n;
while(~scanf("%d",&t))
{
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&str[i]);
dp[0]=str[0];
for(int i=1;i<n;i++)
dp[i]=max(dp[i-1]+str[i],str[i]);//对于dp[i],要么在dp[i-1]的基础上加上str[i],要么是直接只有一个元素str[i]
lm[0]=str[0];
rm[n-1]=str[n-1];
for(int i=1;i<n;i++)
lm[i]=max(lm[i-1],dp[i]);//对于lm[i],它的值可能与它前一个的值相同,也可能是以i元素结束的序列的最大值,即dp[i]

dp[n-1]=str[n-1];
for(int i=n-2;i>=0;i--)
dp[i]=max(dp[i+1]+str[i],str[i]);//记得反方向求dp[i]
for(int i=n-2;i>=0;i--)
rm[i]=max(rm[i+1],dp[i]);//同理
int maxs=-0x3f3f3f3f;
for(int i=1;i<n;i++)
if(maxs < lm[i-1]+rm[i])
maxs=lm[i-1]+rm[i];
printf("%d\n",maxs);
}
}
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值