题目描述
总时间限制: 1000ms内存限制: 65536kB
描述
Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
1
2
3
4
5t1 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
2
31 10 1 -1 2 2 3 -3 4 -4 5 -5
样例输出
113
提示
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])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53#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内容请搜索靠谱客的其他文章。
发表评论 取消回复