[POJ2559]Largest Rectangle in a Histogram

题目链接:http://poj.org/problem?id=2559

 

求所给柱状图内面积最大的矩形。

用了一个叫做单调栈的玩意,思路很像DP,就是每一个柱看作一个结构体,保存当前柱的高度以及它之前(左侧)所能到达的最大横坐标距离,且只有满足条件的时候才会入栈。

 1 #include <algorithm>
 2 #include <iostream>
 3 #include <iomanip>
 4 #include <cstring>
 5 #include <climits>
 6 #include <complex>
 7 #include <fstream>
 8 #include <cassert>
 9 #include <cstdio>
10 #include <bitset>
11 #include <vector>
12 #include <deque>
13 #include <queue>
14 #include <stack>
15 #include <ctime>
16 #include <set>
17 #include <map>
18 #include <cmath>
19 
20 using namespace std;
21 
22 typedef __int64 LL;
23 const int maxn = 100010;
24 typedef struct Node {
25     LL h;
26     int p;
27     Node(LL _h, LL _p) : h(_h), p(_p) {}
28 };
29 
30 inline LL max(LL a, LL b) {
31     return a > b ? a : b;
32 }
33 
34 int n;
35 LL h[maxn];
36 LL ans;
37 stack<Node> st;
38 
39 int main() {
40     // freopen("in", "r", stdin);
41     while(~scanf("%d", &n) && n) {
42         h[n] = 0;
43         while(!st.empty())    st.pop();
44         ans = 0;
45         Node tmp(-1, 0);
46         st.push(tmp);
47         for(int i = 0; i < n; i++) {
48             scanf("%I64d", &h[i]);
49         }
50         LL cur = 0;
51         for(int i = 0; i <= n; i++) {
52             tmp.h = h[i], tmp.p = i + 1;
53             while(st.top().h > tmp.h) {
54                 tmp = st.top();
55                 st.pop();
56                 ans = max(ans, (i+1-tmp.p)*tmp.h);
57             }
58             st.push(Node(h[i], tmp.p));
59         }
60         printf("%I64d\n", ans);
61     }
62     return 0;
63 }

 

posted @ 2015-10-06 15:11  Kirai  阅读(164)  评论(0编辑  收藏  举报