关于单调栈的性质,和单调队列基本相同,只不过单调栈只使用数组的尾部, 类似于栈。
Accepted Code:
1 /*************************************************************************
2 > File Name: 2796.cpp
3 > Author: Stomach_ache
4 > Mail: sudaweitong@gmail.com
5 > Created Time: 2014年07月21日 星期一 22时45分56秒
6 > Propose:
7 ************************************************************************/
8 #include <cmath>
9 #include <string>
10 #include <cstdio>
11 #include <fstream>
12 #include <cstring>
13 #include <iostream>
14 #include <algorithm>
15 using namespace std;
16
17 typedef long long LL;
18 const int maxn = 100005;
19 int n;
20 // b[i] holds the smallest index where a[b[i]]...a[i] are not larger than a[i], and e[i] is similar, just extends to the right of a[i]
21 int a[maxn], b[maxn], e[maxn], st[maxn];
22 LL sum[maxn]; //prefix sum
23
24 int
25 main(void) {
26 #ifndef ONLINE_JUDGE
27 freopen("in.txt", "r", stdin);
28 #endif
29 while (~scanf("%d", &n)) {
30 for (int i = 1; i <= n; i++) scanf("%d", a+i);
31 for (int i = 1; i <= n; i++) b[i] = e[i] = i;
32 sum[0] = 0;
33 for (int i = 1; i <= n; i++) {
34 sum[i] = sum[i-1] + a[i];
35 }
36 // the top of no decreasing stack
37 int top = 0;
38 for (int i = 1; i <= n; i++) {
39 if (!top || a[i] > a[st[top-1]]) {
40 // push an element to stack
41 st[top++] = i;
42 } else {
43 while (top > 0 && a[st[top-1]] > a[i]) {
44 // update e[st[top-1]]
45 e[st[top-1]] = i - 1;
46 // update b[i]
47 b[i] = b[st[top-1]];
48 // pop the toppest element of stack
49 top--;
50 }
51 if (!top || a[st[top-1]] != a[i]) {
52 // push
53 st[top++] = i;
54 } else if(a[st[top-1] == a[i]]) {
55 // update b[i]
56 b[i] = b[st[top-1]];
57 }
58 }
59 }
60 // update e[i] of those elements that still in the stack
61 for (int i = 0; i < top; i++) e[st[i]] = n;
62 // find the answer
63 LL ans = -1, bb, ee;
64 for (int i = 1; i <= n; i++) {
65 if (ans < a[i] * (sum[e[i]]-sum[b[i]-1])) {
66 ans = a[i] * (sum[e[i]]-sum[b[i]-1]);
67 bb = b[i];
68 ee = e[i];
69 }
70 }
71 printf("%lld
%lld %lld
", ans, bb, ee);
72 }
73
74 return 0;
75 }