最大连续子序列和(经典DP) 之 hdu 1231 最大连续子序列

//  [8/1/2014 Sjm]
/*
经典问题。。。
状态:以当前位置i结尾的最大连续子序列和
*/

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cmath>
 5 #include <string>
 6 #include <algorithm>
 7 #include <cstring>
 8 #include <set>
 9 #include <utility>
10 #include <locale>
11 #include <ctime>
12 using namespace std;
13 //using int64 = long long;
14 const int INF = 0x3f3f3f3f;
15 const int MaxN = 10010;
16 
17 int N, arr[MaxN];
18 
19 void Solve()
20 {
21     int ans = -1, maxTmp = -1;
22     int beginTmp = 0, endTmp = 0, ibegin = 0, iend = 0;
23     for (int i = 0; i < N; ++i)
24     {
25         if (maxTmp < 0)
26         {
27             maxTmp = arr[i];
28             beginTmp = i;
29             endTmp = i;
30         }else
31         {
32             maxTmp += arr[i];
33             endTmp = i;
34         }
35         if (maxTmp > ans)
36         {
37             ans = maxTmp;
38             //cout << "---" << ans << endl;
39             ibegin = beginTmp;
40             iend = endTmp;
41         }
42     }
43     cout << ans << " " << arr[ibegin] << " " << arr[iend] << endl;
44 }
45 
46 int main()
47 {
48 #ifdef HOME
49     freopen("in", "r", stdin);
50     //freopen("out", "w", stdout);
51 #endif
52     
53     while (cin >> N && N)
54     {
55         bool judge = true;
56         for (int i = 0; i < N; ++i) {
57             cin >> arr[i];
58             if (arr[i] >= 0) judge = false;
59         }
60         if (judge)
61         {
62             cout << 0 << " " << arr[0] << " " << arr[N - 1] << endl;
63         }
64         else
65         {
66             Solve();
67         }
68     }
69 
70 #ifdef HOME
71     cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
72 #endif
73     return 0;
74 }


 
原文地址:https://www.cnblogs.com/shijianming/p/4140808.html