ACM: 动态规划 poj 2479
来源:互联网 发布:linux ed2k 终端 编辑:程序博客网 时间:2024/06/03 22:44
Description
Given a set of n integers:A={a1, a2,..., an}, we define a function d(A) as below: Your taskis to calculate d(A).
Input
The input consists ofT(<=30) test cases. The number of test cases (T) isgiven in the first line of the input.
Each test case contains two lines. The first line is an integern(2<=n<=50000). The second linecontains n integers: a1, a2, ..., an. (|ai| <=10000).There is an empty line after each case.
Each test case contains two lines. The first line is an integern(2<=n<=50000). The second linecontains n integers: a1, a2, ..., an. (|ai| <=10000).There is an empty line after each case.
Output
Print exactly one line for eachtest 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
题意: 序列分成两部分, 两部分的连续和再加起来最大的值.
解题思路:
1. 动态规划. max_left[i]表示左边前i个最大连续和.
max_right[i]表示右边前i个最大连续和.
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 50005
int n;
int a[MAX];
int max_left[MAX];
int max_right[MAX];
int maxsize, temp;
inline int max(int a,int b)
{
return a > b ? a : b;
}
int main()
{
int casenum;
//freopen("input.txt","r",stdin);
scanf("%d",&casenum);
while(casenum--)
{
scanf("%d",&n);
memset(max_left,0,sizeof(max_left));
memset(max_right,0,sizeof(max_right));
for(int i = 0; i < n; ++i)
{
scanf("%d",&a[i]);
}
temp = maxsize = -(1<<29);
for(int i = 0; i < n; ++i)
{
if(temp >= 0)
temp += a[i];
else
temp = a[i];
maxsize = max(maxsize,temp);
max_left[i] = maxsize;
}
temp = maxsize = -(1<<29);
for(int i = n-1; i >= 0; --i)
{
if(temp >= 0)
temp += a[i];
else
temp = a[i];