您的位置:首页 > 其它

POJ 2479 动态规划 最大子段和

2018-04-02 15:24 405 查看

POJ 2479 最大子段和 动态规划解法

题目链接点这里

Maximum sum

Time Limit: 1000MS Memory Limit: 65536K

Total Submissions: 42766 Accepted: 13308

Description

Given a set of n integers: A={a1, a2,…, an}, we define a function d(A) as below:



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.

好了,我是专门为了练习动态规划搜的题,解法自然是动态规划,动态规划也是最高效的解法

首先分析题目,可知,是要求一个数组中 前半段最大子段和 和 后半段最大子段和 的和最大。(仿佛表达的更加混乱)。

这道题像是普通求最大子段和的升级版,先说一下普通的求最大子段和

动态规划的核心是状态 和状态转移方程。

我们定义d[i]表示以第i个元素结束(正向)的子段的最大子段和

那么状态转移方程则是:d[i] = max(d[i-1]+a[i],a[i]);

取一个res初始化为大负数,然后res = max(res,d[i]);

直接一趟for循环走完,最后res即为所求的值。

对于这道题,

我的思路是正向(从0开始)求一趟d[]数组,d[i]表示以第i个元素结束的子段的最大子段和,反向(从n-1开始)求一趟数组rev_d[],rev_d[i]表示以第i个元素结束的子段的最大子段和。求法和上面的普通的求最大子段和相同。

同时,还需要两个数组fir_max,sec_max,fir_max[i]表示从0-i个元素上最大子段和,sec_max[i]表示从i到n-1个元素上的最大子段和。

最后,定义一个res初始化为大负数,然后res = max(res,fir_max[i]+sec_max[i+1]);

最后直接输出res即可

AC代码如下:通过时间为400ms左右,看了别人的题解,好像都差不多安

#include <stdio.h>
#define fur(i,a,b) for(int i=(a);i<(b);i++)
#define furr(i,a,b) for(int i=(a);i>(b);i--)
#define max(a,b) ( ((a)>(b)) ? (a):(b) )
#define min(a,b) ( ((a)>(b)) ? (b):(a) )
#define cl(a, b) memset((a),1,sizeof(a))
#define Point int
#define null NULL
#define OFFSET 500000
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const double eps=1e-8;
using namespace std;

int main()
{
int T;
int a[50002];
int d[50002],rev_d[50002];
int fir_max[50002],sec_max[50002];
int n;
int res;

scanf("%d",&T);
while(T--)
{
res = -999999;
scanf("%d",&n);
fur(i,0,n)
scanf("%d",&a[i]);
d[0] = a[0];
rev_d[n-1] = a[n-1];
fir_max[0] =d[0];
sec_max[n-1] = rev_d[n-1];
for(int i=1,j=n-2;i<n-1;i++,j--)
{
d[i] = max((d[i-1]+a[i]),a[i]);
fir_max[i] = max(fir_max[i-1],d[i]);
rev_d[j] = max((rev_d[j+1]+a[j]),a[j]);
sec_max[j] = max(sec_max[j+1],rev_d[j]);
}
fur(i,0,n-1)
//printf("%d-%d:%d,%d-%d:%d\n",0,i,fir_max[i],i+1,n-1,sec_max[i+1]);
res = max(res,fir_max[i]+sec_max[i+1]);
printf("%d\n",res);
}
return 0;
}


写在后面:

1,compile error了好多次,POJ不支持memory.h还是咋的

2.WA了好多次,才反应过来,res初始化时得初始化为一个大负数,我一开始直接给的0。。。

3.本题必须使用scanf输入,貌似cin会超时。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息