1. 程式人生 > >[POJ2559]Largest Rectangle in a Histogram (棧)

[POJ2559]Largest Rectangle in a Histogram (棧)

題意

如圖所示,在一條水平線上有n個寬為1的矩形,求包含於這些矩形的最大子矩形面積(圖中的陰影部分的面積即所求答案)。

思路

一個很老的,也是一個很好的題目。

維護一個單調棧即可。

不過在洛谷SP1805裡是藍題,還真是意外呢。

程式碼

#include <iostream>
#include <cstdio>
using namespace std;
#define N 100005
struct Elem
{
    int height;
    int count;
}stack[N];
int top;
int main()
{
    
int height, n; long long ans, tot, tmp; while (scanf("%d", &n) != EOF && n) { top = 0; ans = 0; for (int i = 0; i < n; ++i) { scanf("%d", &height); tmp = 0; while (top > 0 && stack[top - 1
].height >= height) { tot = stack[top - 1].height * (stack[top - 1].count + tmp); if (tot > ans) ans = tot; tmp += stack[top - 1].count; --top; } stack[top].height = height; stack[top].count
= 1 + tmp; ++top; } tmp = 0; while (top > 0) { tot = stack[top - 1].height * (stack[top - 1].count + tmp); if (tot > ans) ans = tot; tmp += stack[top - 1].count; --top; } printf("%lld\n", ans); } return 0; }