[openjudge-动态规划]Maximum sum

xiaoxiao2021-02-28  97

题目描述

题目原文

描述

Given a set of n integers: A={a1, a2,…, an}, we define a function d(A) as below: d(A)=max(t1i=s1ai+t2j=s2aj|1<=s1<=t1<s2<=t2<=n) d ( A ) = max ( ∑ i = s 1 t 1 a i + ∑ j = s 2 t 2 a j | 1 <= s 1 <= t 1 < s 2 <= t 2 <= n ) Your task is to calculate d(A).

输入

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.

输出

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

样例输入

1

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

样例输出

13

提示

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

Huge input,scanf is recommended.

来源

POJ Contest,Author:Mathematica@ZSU

翻译

描述

给定一组N个整数:A ={A1,A2,…,An},我们定义一个函数D(A)如下: d(A)=max(t1i=s1ai+t2j=s2aj|1<=s1<=t1<s2<=t2<=n) d ( A ) = max ( ∑ i = s 1 t 1 a i + ∑ j = s 2 t 2 a j | 1 <= s 1 <= t 1 < s 2 <= t 2 <= n ) 你的任务是计算D(A)。

输入

输入包括T(T<=30)的测试数据。 测试数据的数目(T),在输入的第一行。每个测试用例包含两行。 第一行是整数n(2<= N <=50000)。第二行包含n个整数: A1A2...An|Ai|<=10000 A 1 , A 2 , . . . , A n 。 ( | A i | <= 10000 ) 。每个样例例后有一个空行。

输出

每个测试用例只有一行,该行应包含整数D(A)。

提示

在示例中,我们选择{2,2,3,-3,4}和{5},那么我们就可以得到答案。 在有巨大的输入数据时,scanf是最高效的。

来源

POJ 竞赛,作者:Mathematica@ZSU

分析

这是一道比较经典的动态规划题。这道题的难点主要是在怎样将问题分解。我们先从一个点开始,假定这个点的左边有一个最大子段,右边也有一个最大子段。那答案就是每个点左右最大子段的和的最大值。那怎么左右最大字段和呢?我们可以计算左边和右边到i-1,i+1点的最大和,再求i点的最大和,递推公式为: 第一步: leftsum[i]=max(a[i],a[i]+leftsum[i1]) l e f t s u m [ i ] = max ( a [ i ] , a [ i ] + l e f t s u m [ i − 1 ] ) rightsum[i]=max(a[i],a[i]+rightsum[i+1]) r i g h t s u m [ i ] = max ( a [ i ] , a [ i ] + r i g h t s u m [ i + 1 ] ) 第二步: leftsum[i]=max(leftsum[i],leftsum[i1]) l e f t s u m [ i ] = max ( l e f t s u m [ i ] , l e f t s u m [ i − 1 ] ) rightsum[i]=max(rightsum[i],rightsum[i+1]) r i g h t s u m [ i ] = max ( r i g h t s u m [ i ] , r i g h t s u m [ i + 1 ] ) 第三步: d(A)=max(leftsum[i]+rightsum[i+1]) d ( A ) = max ( l e f t s u m [ i ] + r i g h t s u m [ i + 1 ] ) 最后输出d(A)即可。

实现

#include<bits/stdc++.h> using namespace std; int n,a[50005],fa[50005],fb[50005],maxx; int main() { int T; scanf("%d",&T); while(T--) { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); fa[1]=a[1]; for(int i=2;i<=n;i++) fa[i]=max(a[i],a[i]+fa[i-1]); fb[n]=a[n]; for(int i=n-1;i>0;i--) fb[i]=max(a[i],a[i]+fb[i+1]); for(int i=2;i<=n;i++) fa[i]=max(fa[i],fa[i-1]);//求到位置i左边的最大序列 for (int i=n-1;i>0;i--) fb[i]=max(fb[i],fb[i+1]);//求到位置i右边的最大序列 maxx=fa[1]+fb[2]; for(int i=1;i<n;i++) maxx=max(maxx,fa[i]+fb[i+1]);//找不同位置i的d(A)值,求出最大值 printf("%d\n",maxx); } }
转载请注明原文地址: https://www.6miu.com/read-59202.html

最新回复(0)