poj2559/SP1805 Largest Rectangle in a Histogram

单调栈例题,很早就搞懂了,但一直没有机会实现。

今天决定来实现一下,结果发现还是有很多细节要注意。(WA了两次)

方法的话百度单调栈就好了,我就不再重复了。

说一下容易错的的细节。

1.Long long。

2.最后要把栈内剩余矩形进行统计。可以采用push一个 高为0的矩形 来实现以减少代码长度。

3.如果你是用STL来实现栈的,注意栈空的时候是没有栈顶元素的,要加上特判(详见代码)。

好了,上代码。

 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 }
原文地址:https://www.cnblogs.com/wsmrxc/p/8973414.html