1. 程式人生 > >POJ2479【線性DP】

POJ2479【線性DP】

看完題還懵逼了。。。

題意:

給一個序列,求連續兩個序列的最大值。

思路:

正著做一次一段連續序列的最大值。
反著做一次一段連續序列的最大值。
然後對每個位置可得前面最大+後面最大,判斷列舉一下就好了。

//#include <bits/stdc++.h>
#include<iostream>
#include<vector>
#include<cstdio>
#include<string.h>
#include<algorithm>
using namespace std;
typedef pair<int
,int> PII; typedef long long LL; //#pragma comment(linker, "/STACK:102400000,102400000") const int INF=0x3f3f3f3f; const int N=5e4+10; int n; int a[N]; int temp1[N],temp2[N]; void solve1(){ int cur = a[1]; int ans = a[1]; temp1[1]=ans; for(int i=2;i<=n;i++){ if(cur > 0) cur += a[i]; else
cur = a[i]; if(cur > ans) ans = cur; temp1[i] = ans; } } void solve2(){ int cur = a[n]; int ans = a[n]; temp2[n]=ans; for(int i=n-1;i>=1;i--){ if(cur>=0) cur += a[i]; else cur = a[i]; if(cur > ans) ans = cur; temp2[i] = ans; } } int
main(){ int T; scanf("%d",&T); while(T--){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); memset(temp1,0,sizeof(temp1)); memset(temp2,0,sizeof(temp2)); solve1(); solve2(); int ans=-INF; for(int i=1;i<n;i++) ans = max(temp1[i]+temp2[i+1],ans); printf("%d\n",ans); } return 0; }