Monotonic stack example, I understood it very early, but I have never had the opportunity to implement it.
Today I decided to implement it, and it turned out that there are still many details to pay attention to. (was twice)
If the method is the Baidu monotonic stack, I will not repeat it.
Talk about fallible details.
1.Long long。
2. Finally, count the remaining rectangles in the stack. It can be achieved by pushing a rectangle with a height of 0 to reduce the code length.
3. If you use STL to implement the stack, note that there is no top element of the stack when the stack is empty, and a special judgment should be added (see the code for details).
OK, let's code.
1 #include <cstdio>
2 #include <cstring>
3 #include <stack>
4 #include <algorithm>
5 #include <iostream>
6 using namespace std;
7 typedef long long ll;
8 const int MAXN = 100000 + 20;
9
10 inline ll read()
11 {
12 ll x = 0; char ch = getchar();
13 while(!isdigit(ch)) ch = getchar();
14 while(isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
15 return x;
16 }
17
18 ll N;
19
20 struct rec
21 {
22 ll l, h;
23 rec(ll l = 0, ll h = 0) : l(l), h(h) {}
24 };
25
26 struct _stack
27 {
28 stack<rec> sta;
29
30 inline void init()
31 {
32 while(!sta.empty())
33 sta.pop();
34 }
35
36 inline ll Pushin(rec cur)
37 {
38 if(sta.empty() || sta.top().h < cur.h)//注意sta.empty()的特判
39 {
40 sta.push(cur);
41 return 0;
42 }
43
44 ll len = 0, area = 0;
45 rec now;
46 while(!sta.empty() && sta.top().h > cur.h)//同上
47 {
48 now = sta.top();
49 len += now.l;
50 area = max(area, len * now.h);
51 sta.pop();
52 }
53 sta.push(rec(len + cur.l, cur.h));
54 return area;
55 }
56 }Stack;
57
58 int main()
59 {
60 while(cin>>N, N)
61 {
62 Stack.init();
63 ll ans = 0;
64 for(ll i = 1; i <= N; i++)
65 ans = max(ans, Stack.Pushin(rec(1, read())));
66 ans = max(ans, Stack.Pushin(rec(1, 0)));
67 cout<<ans<<endl;
68 }
69 return 0;
70 }