POJ 2479 Maximum Sum (DP)
题意:给定n个数,求两段连续子列的最大和。
思路:先从左向右dp,求出一段连续子列的最大和,再从右向左dp,求出两段连续子列的最大和,方法还是挺经典的。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <memory.h>
#include <cmath>
#include <bitset>
#include <queue>
#include <vector>
using namespace std;
const int MAXN = 100400;
const int INF = 0x4ffffff;
#define CLR(x,y) memset(x,y,sizeof(x))
#define ADD(x) x=((x+1)&BORDER)
#define IN(x) scanf("%d",&x)
#define OUT(x) printf("%d\n",x)
#define MIN(m,v) (m)<(v)?(m):(v)
#define MAX(m,v) (m)>(v)?(m):(v)
#define ABS(x) ((x)>0?(x):-(x))
int arr[MAXN],dp[MAXN];
int sum,n,ans;
int init()
{
sum = 0;
ans = -INF;
CLR(dp,0);
return 0;
}
int input()
{
for(int i = 0; i < n; ++i)
IN(arr[i]);
return 0;
}
int work()
{
int i,j,tmp;
tmp = -INF;
for(i = 0; i < n; ++i)
{
sum += arr[i];
tmp = MAX(tmp,sum);
dp[i] = tmp;
sum = MAX(sum,0);
}
sum = 0;
tmp = -INF;
for(i = n-1; i > 0; --i)
{
sum += arr[i];
tmp = MAX(sum,tmp);
sum = MAX(sum,0);
ans = MAX(tmp+dp[i-1],ans);
}
OUT(ans);
return 0;
}
int main()
{
int tt;
while(IN(n))
{
if(!n)
break;
init();
input();
work();
}
return 0;
}