C++动态规划算法之Maximum sum(最大和)

xiaoxiao2021-02-28  110

Maximum sum(最大和)

Description

Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below: t1 t2 d(A) = max{ ∑ai + ∑aj | 1 <= s1 <= t1 < s2 <= t2 <= n } i=s1 j=s2 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

大意

给定一组N个整数:A ={A1,A2,...,An},我们定义一个函数D(A)如下: ……

你的任务是计算d(A)。输入包括T(<=30)的测试数据。 测试数据的数目T,在输入的第一行。每个测试用例包含两个行。 第一行是整数N(2<= N <=50000)。 第二行包含N个整数:A1,A2,...,An。 (|Ai|<=10000)。每个案例后有一个空行。打印每个测试用例只有一个行,该行应包含整数d(A)。 在示例中,我们选择{2,2,3,-3,4}和{5},那么我们就可以得到答案。

解题

看到这道题时,我想到了两种方法——深搜(TLE)、动态规划(AC)。

方法壹:深搜

状态:

Time Limit Exceeded

#include<bits/stdc++.h> using namespace std; int maxn,sum,n,a[50001]; bool flag=1; //用于判断是否截了第二段数 void dfs(int x) { if(x<=n) //判断是不是枚举完了所有数 { sum+=a[x]; if(flag) //判断是否截了第二段数 { flag=0; for(int j=x+1;j<=n;j++)dfs(j); //枚举第二段数起始位置 flag=1; } dfs(x+1); if(!flag)maxn=max(sum,maxn); //if用于判断是不是截了两段数 sum-=a[x]; //回溯 } } int main() { int t; cin>>t; while(t--) { cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) dfs(i); //枚举第一段数起始位置 cout<<maxn<<endl; } }

方法贰:动态规划

状态:

Accepted

#include<bits/stdc++.h> using namespace std; int n,maxn,a[50001],f[50001],g[50001],F[50001],G[50001]; main() { int t; cin>>t; while(t--) { maxn=-20001; cin>>n>>a[1]; int mxf=F[1]=f[1]=a[1]; for(int i=2;i<=n;i++) { cin>>a[i]; f[i]=a[i]+max(0,f[i-1]); //找出在a[1]……a[i]序列中以a[i]为结尾的和最大子序列 mxf=F[i]=max(mxf,f[i]); //找出在a[1]……a[i]序列中的和最大子序列(不一定包含a[i]) } int mxg=G[n]=g[n]=a[n]; for(int i=n-1;i>0;i--) { g[i]=a[i]+max(0,g[i+1]); //找出在a[i]……a[n]序列中以a[i]为开头的和最大子序列 mxg=G[i]=max(mxg,g[i]); //找出在a[i]……a[n]序列中的和最大子序列(不一定包含a[i]) } for(int i=1;i<n;i++) //枚举断点 if(F[i]+G[i+1]>maxn) //G[i+1]是因为不可有重叠部分 maxn=F[i]+G[i+1]; cout<<maxn<<endl; } }

转载请注明原文地址: https://www.6miu.com/read-57402.html

最新回复(0)