2593:Max Sequence
-
总时间限制:
- 3000ms 内存限制:
- 65536kB
-
描述
-
Give you N integers a1, a2 ... aN (|ai| <=1000, 1 <= i <= N).
You should output S.
输入
- 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. 输出
- For each test of the input, print a line containing S. 样例输入
-
5 -5 9 -5 11 20 0
样例输出
-
40
来源
- POJ Monthly--2005.08.28,Li Haoyuan
- ************************************************
- 这道题和2479题一样。昨晚想了想2479的算法,还是有点明白了。毕竟dp[i]表示的是从1到i最大的序列和,如果前面dp[i-1]小于0的话,那肯定不能把当前值a[i]加到上面去了,因为那样肯定不是最大的,所以要重新开始一段。可是还是有没懂的地方,比如为什么计算完一遍dp的值之后还要进行那个包含max的循环,在i-1(i+1)和i中挑一个大的?但是算法总归还是半理解并且记住了.
-
/* //dpleft[i]表示从1到i的最大子序列和,dpright[i]表示从i到n的最大子序列和 */ #include <cstdio> #include <algorithm> using namespace std; int dpleft[100005],dpright[100005]; int a[100005]; int main() { int n; while(scanf("%d",&n)!=EOF){ if(n==0) break; for(int i=1;i<=n;i++){ scanf("%d",&a[i]); } dpleft[1]=a[1]; for(int i=2;i<=n;i++){ if(dpleft[i-1]>0) dpleft[i]=dpleft[i-1]+a[i]; else dpleft[i]=a[i]; } for(int i=2;i<=n;i++){ dpleft[i]=max(dpleft[i-1],dpleft[i]); } dpright[n]=a[n]; for(int i=n-1;i>=1;i--){ if(dpright[i+1]>0) dpright[i]=dpright[i+1]+a[i]; else dpright[i]=a[i]; } //要从后往前,因为n那一头是固定的,变的是区间左端点 for(int i=n-1;i>=1;i--){ dpright[i]=max(dpright[i],dpright[i+1]); } int m=dpleft[1]+dpright[2]; for(int i=2;i<=n-1;i++){ m=max(m,dpleft[i]+dpright[i+1]); } printf("%d\n",m); } return 0; }
*********************** - 坚持,胜利就在眼前~