(線性dp)POJ2593 Max Sequence
阿新 • • 發佈:2019-03-11
con bre plm algo http spa amp code image Max Sequence
You should output S.
For each test of the input, print a line containing S.
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 18511 | Accepted: 7743 |
Description
Give you N integers a1, a2 ... aN (|ai| <=1000, 1 <= i <= N).You should output S.
Input
The input will consist of several test cases. For each test case, one integer N (2 <= N <= 100000) is given in the first line. Second line contains N integers. The input is terminated by a single line with N = 0.Output
Sample Input
5 -5 9 -5 11 20 0
Sample Output
40
最大連續和的升級版,最大連續和的狀態轉移式為:dp[i] = max(dp[i-1] + a[i],a[i])
這個題中從左邊開始遍歷一次,從右邊遍歷一次,分成兩部分,然後相加,取最大值。
C++代碼
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> usingnamespace std; const int maxn = 100005; int a[maxn],dpl[maxn],dpr[maxn],m1[maxn],m2[maxn]; int Inf = -0x3f3f3f3f; int main(){ int n; while(~scanf("%d",&n)){ if(n==0) break; for(int i = 1; i <= n; i++){ scanf("%d",&a[i]); } memset(dpl,0,sizeof(dpl)); memset(dpr,0,sizeof(dpr)); m1[0] = m2[n+1] = Inf; for(int i = 1; i <= n; i++){ dpl[i] = max(dpl[i-1] + a[i],a[i]); if(m1[i-1] < dpl[i]) m1[i] = dpl[i]; else m1[i] = m1[i-1]; } for(int i = n; i >= 1; i--){ dpr[i] = max(dpr[i+1] + a[i],a[i]); if(m2[i+1] < dpr[i]) m2[i] = dpr[i]; else m2[i] = m2[i+1]; } int maxsum = Inf; int tmp[maxn]; for(int i = 1; i <= n-1; i++){ tmp[i] = m1[i] + m2[i+1]; if(maxsum < tmp[i]) maxsum = tmp[i]; } printf("%d\n",maxsum); } return 0; }
(線性dp)POJ2593 Max Sequence