POJ 2479 Maximum sum 解题报告

Maximum sum
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 40596   Accepted: 12663

Description

Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:

POJ 2479 Maximum sum 解题报告

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

题目大意:给定一个整数数字序列s,要求使两段不相交的子序列s1,s2的和最大

题解:动态规划

ls[i]表示以第i个元素结尾序列的最大值

rs[i]表示以第i个元素开始序列的最大值

rst[i]表示取i个元素能够达到的最大值

所以有

ls[i]=max(ls[i-1]+a[i], a[i]),  rs[i]=max(rs[i+1]+a[i], a[i])

rst[i]=max(rst(i+1), rs[i])

所以最后的答案是s=max(s, ls[i]+rst(i+1))

#include <stdio.h>
#include <string.h>
#include <cstdio>
#include <iostream> using namespace std; const int maxn = 1e6+7, inf = -1e6+7; int a[maxn], ls[maxn], rs[maxn], s, rst[maxn]; int main()
{
int t, n;
scanf("%d", &t);
while (t--)
{
s = 0;
memset(ls, 0, sizeof(ls));
memset(rs, 0, sizeof(rs));
memset(rst, 0, sizeof(rst));
scanf("%d", &n);
for (int i=0; i<n; i++)
scanf("%d", &a[i]);
ls[0] = a[0];
for (int i=1; i<n; i++) {
ls[i] = max(ls[i-1]+a[i], a[i]);
}
rst[n-1] = rs[n-1] = a[n-1];
for (int i=n-2; i>=0; i--){
rs[i] = max(rs[i+1]+a[i], a[i]);
rst[i] = max(rst[i+1], rs[i]);
}
s = inf;
for (int i=0; i<n-1; i++) {
s = max(s, ls[i]+rst[i+1]);
}
printf("%d\n", s);
}
return 0;
}
上一篇:SQL 优化tips


下一篇:nginx反向代理取得IP地址