POJ 2479 DP

链接:

http://poj.org/problem?id=2479

题意:

求两个不相交的最大字段和

题解:

对于每个i来说,找出0~i-1的最大字段和和i~n-1的最大字段和,在加起来求最大值

代码:

31 int a[MAXN];
32 int l[MAXN];
33 int r[MAXN];
34 
35 int main() {
36     int T;
37     cin >> T;
38     while (T--) {
39         int n;
40         cin >> n;
41         rep(i, 0, n) scanf("%d", a + i);
42         l[0] = a[0];
43         rep(i, 1, n) {
44             if (l[i - 1] < 0) l[i] = a[i];
45             else l[i] = l[i - 1] + a[i];
46         }
47         rep(i, 1, n) l[i] = max(l[i], l[i - 1]);
48         r[n - 1] = a[n - 1];
49         per(i, 0, n - 1) {
50             if (r[i + 1] < 0) r[i] = a[i];
51             else r[i] = r[i + 1] + a[i];
52         }
53         per(i, 0, n - 1) r[i] = max(r[i], r[i + 1]);
54         int res = -INF;
55         rep(i, 1, n) res = max(res, l[i - 1] + r[i]);
56         cout << res << endl;
57     }
58     return 0;
59 }

 

posted @ 2017-04-25 18:02  Flowersea  阅读(152)  评论(0编辑  收藏  举报