POJ2559 Largest Rectangle in a Histogram
阿新 • • 發佈:2021-07-21
傳送
單調棧經典題,以前總寫不對,有些心裡陰影,故在此放一個程式碼。
其主要思路就是保持棧一直單調遞增,然後只有在被彈棧的時候才統計以這個豎塊為左邊界的矩形的面積。
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<cstdlib> #include<cctype> #include<vector> #include<queue> #include<assert.h> #include<ctime> using namespace std; #define enter puts("") #define space putchar(' ') #define Mem(a, x) memset(a, x, sizeof(a)) #define In inline #define forE(i, x, y) for(int i = head[x], y; ~i && (y = e[i].to); i = e[i].nxt) typedef long long ll; typedef double db; const int INF = 0x3f3f3f3f; const db eps = 1e-8; const int maxn = 1e5 + 5; In ll read() { ll ans = 0; char ch = getchar(), las = ' '; while(!isdigit(ch)) las = ch, ch = getchar(); while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar(); if(las == '-') ans = -ans; return ans; } In void write(ll x) { if(x < 0) x = -x, putchar('-'); if(x >= 10) write(x / 10); putchar(x % 10 + '0'); } In void MYFILE() { #ifndef mrclr freopen(".in", "r", stdin); freopen(".out", "w", stdout); #endif } int n; struct Node { int h, w; }st[maxn]; int top = 0; ll ans = 0; In void Push(int h) { if(!top || h > st[top].h) st[++top] = (Node){h, 1}; else { int tp = 0; while(top && st[top].h >= h) { ans = max(ans, 1LL * st[top].h * (st[top].w + tp)); tp += st[top--].w; } st[++top] = (Node){h, tp + 1}; } } int main() { // MYFILE(); while(scanf("%d", &n) && n) { ans = top = 0; for(int i = 1; i <= n; ++i) Push(read()); Push(0); write(ans), enter; } return 0; }