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.
题意:求两个不相交串的和的最大值
思路:利用前缀和,从左到右先记录[1,i]序列中的和的最大值,然后从右往左再找和的最大值
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
using namespace std;
const int INF = 1<<29;
const int MAX = 50050;
int n;
int dp[MAX];//dp[i]表示范围在[1,i]内的最大的子段的和
int A[MAX];
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
scanf("%d", &n);
int tmp = -INF;
int sum = 0;
//从左到右找最大子段
for (int i = 1; i <= n; i++)
{
scanf("%d", &A[i]);
sum += A[i];
if (sum > tmp)
tmp = sum;
dp[i] = tmp;
if (sum < 0)
sum = 0;
}
tmp = -INF; sum = 0;
int ans = -INF;
//从右到左找最大子段
for (int i = n; i >= 2; i--)
{
sum += A[i];
if (sum > tmp)
tmp = sum;
if (sum < 0)
sum = 0;
if (tmp + dp[i-1] > ans)
ans = tmp + dp[i-1];
}
printf("%d\n", ans);
}
return 0;
}