概述
题目描述
总时间限制: 1000ms内存限制: 65536kB
描述
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).
输入
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.
问题解决
动态规划主要是两个方向,从左往右和从右往左,从左往右做两遍,第一遍找到当前的最大和,第二遍找左边能达到的最大值,从右往左做一遍即可。
第一遍:dp[i]=max(dp[i-1]+arr[i],arr[i])
#include <iostream>
#include <algorithm>
#include <string.h>
#include <limits.h>
using namespace std;
int arr[50005];
int dp[50005];
int dp2[50005];
int main(){
int T,n;
cin>>T;
while(T--){
cin>>n;
for(int i=0;i<n;i++){
cin>>arr[i];
}
memset(dp,INT_MIN,sizeof(dp));
dp[0]=arr[0];
for(int i=1;i<n;i++){
dp[i]=max(dp[i-1]+arr[i],arr[i]);
}
for(int i=0;i<n;i++){
cout<<dp[i]<<"
";
}
cout<<endl;
int m=dp[0];dp2[0]=dp[0];
for(int i=1;i<n;i++){
if(dp[i]>m) m=dp[i];
dp2[i] = m;
}
for(int i=0;i<n;i++){
cout<<dp2[i]<<"
";
}
cout<<endl;
dp[n-1] = arr[n-1];
for(int i=n-2;i>=0;i--){
dp[i]=max(dp[i+1]+arr[i],arr[i]);
}
for(int i=0;i<n;i++){
cout<<dp[i]<<"
";
}
cout<<endl;
int sum = INT_MIN;
for(int i=0;i<n-1;i++){
if(dp2[i]+dp[i+1]>sum) sum=dp2[i]+dp[i+1];
}
cout<<sum<<endl;
}
return 0;
}
最后
以上就是清秀云朵为你收集整理的POJ 1481 Maximum sum|动态规划题目描述问题解决的全部内容,希望文章能够帮你解决POJ 1481 Maximum sum|动态规划题目描述问题解决所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复