POJ 2559 Largest Rectangle in a Histogram 單調棧(STL版)

題目鏈接:POJ 2559


代碼如下:

// STL stack版

#include <utility>
#include <cstdio>
#include <stack>
using namespace std;

#define fi first
#define se second
const int N = 111111;
typedef long long ll;
typedef pair<int, int> pii;
ll a[N]; // from 1 to n / [1, n]

struct monotone_stack
{
    stack<pii> sk; // first = startpos, second = index of a[]
    ll mx[N], m;   // mx = max rectangle area through a[i] , m = max(mx[])
    // 棧底元素下標爲0,值爲0
    void clear() {
        m = -(int)1e9;
        while(!sk.empty()) sk.pop();
        sk.push(pii(0, 0));
    }
    void push(int x) {
        while(sk.size() > 1) {
            pii t = sk.top();
            if(a[t.se] > a[x]) {
                mx[t.se] = (x - t.fi) * a[t.se];
                if(m < mx[t.se]) m = mx[t.se];
                sk.pop();
            }
            else break;
        }
        if(a[sk.top().se] == a[x]) sk.push(pii(sk.top().fi, x));
        else sk.push(pii(sk.top().se + 1, x));
    }
    void solve(int x) {  // x is the (end + 1) index of a[]
        while(sk.size() > 1) {
            pii t = sk.top();
            mx[t.se] = (x - t.fi) * a[t.se];
            if(m < mx[t.se]) m = mx[t.se];
            sk.pop();
        }
    }
    ll segm() { return m; }
} s;

int main()
{
    // freopen("in", "r", stdin);
    int n;
    while(scanf("%d", &n), n) {
        s.clear();
        for(int i = 1; i <= n; i++) {
            scanf("%I64d", a + i);
            s.push(i);
        }
        s.solve(n + 1);
        printf("%I64d\n", s.segm());
    }
    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章