侧边栏

HDU-1231 最大连续子序列

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1231

思路:在求最大连续子列和的同时更新左右端点即可,要注意序列最大值不为正数的情况,因为cur和maxn的初值为0

代码:

 1 #include<bits/stdc++.h>
 2 #define inf 0x3f3f3f3f
 3 typedef long long ll;
 4 const int M = int(1e5) * 2 + 5;
 5 using namespace std;
 6 int a[M];
 7 struct sta
 8 {
 9     int sum;
10     int l, r;
11 };
12 sta cur, maxn;
13 int flag;
14 int main()
15 {
16     int k; 
17     while (cin >> k && k)
18     {
19         for (int i = 1; i <= k; i++) cin >> a[i];
20         cur.sum = maxn.sum = -inf;
21         cur.l = cur.r = maxn.l = maxn.r = 1;
22         flag = -inf;
23         for (int i = 1; i <= k; i++)
24         {
25             flag = max(flag, a[i]);
26             cur.sum += a[i]; cur.r=i;
27             if (cur.sum > maxn.sum)
28             {
29                 maxn = cur;
30             }
31             else if (cur.sum < 0)
32             {
33                 cur.sum = 0;
34                 cur.l = cur.r = i + 1;
35             }
36             //cout << " " << cur.sum << " " << maxn.sum << " " <<maxn.l<<" "<<maxn.r<< endl;
37         }
38         if (flag<0) cout << 0 << " " << a[1] << " " << a[k] << endl;
39         else if (!flag) cout << 0 << " " << 0 << " " << 0 << endl;
40         else cout << maxn.sum << " " << a[maxn.l] << " " << a[maxn.r] << endl;
41     }
42     return 0;
43 }

备注:求最大子列和是一个很经典的算法,采用在线处理可以使复杂度降到线性,具体可见百度百科

posted @ 2019-03-10 19:54  晴人  阅读(164)  评论(0编辑  收藏  举报