欢迎找我内推微软

sicily 1091 Maximum Sum (动规)

 1 //1091.Maximum Sum
 2 //b(i,j) = max{b(i,j-1)+a[j], max(b(i-1,t)+a[j])} (t<j)
 3 #include <iostream>
 4 using namespace std;
 5 
 6 int main() {
 7     int t;
 8     cin>>t;
 9     while (t--) {
10         int n;
11         cin>>n;
12         int a[n+1];
13         for (int i = 1; i <= n; i++) cin>>a[i];
14         int b[n+1], c[n+1];
15         c[1] = b[1] = a[1];
16         for (int j = 2; j <= n; j++) {
17             if (b[j-1]<0) {
18                 b[j] = a[j];
19                 c[j] = b[j]>c[j-1]?b[j]:c[j-1];    //这里的c[j-1]刚开始写成了b找了好久才看出来,应该是和以前的b所有而不是上一个b比较
20             } else {
21                 b[j] = b[j-1] + a[j];
22                 c[j] = b[j]>c[j-1]?b[j]:c[j-1];
23             }
24         }
25         b[2] = a[1]+a[2];
26         int max = b[2];
27         for (int j = 3; j <= n; j++) {
28             b[j] = (b[j-1]>c[j-1]?b[j-1]:c[j-1]) + a[j];
29             if (b[j]>max) max = b[j];
30         }
31         cout<<max<<endl;
32     }
33     return 0;
34 }       

 

  正在看《算法设计与分析》的动规3.4 ,因此找了这道题来写。

posted @ 2016-04-24 22:50  zmj97  阅读(214)  评论(0编辑  收藏  举报
欢迎找我内推微软