POJ 2559 Largest Rectangle in a Histogram

来源:互联网 发布:apache ab测试百度 编辑:程序博客网 时间:2024/05/29 01:52

Description
A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles: Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.


【题目分析】
单调栈进阶了。需要用long long就可了。


【代码】

#include <cstdio>using namespace std;const int MAX_N = 100005;int deep[MAX_N], stack[MAX_N], A[MAX_N], n;int main(){    while (scanf("%d", &n) && n)    {        for (int i = 1; i <= n; i++)            scanf("%d", &A[i]);        A[n+1] = 0; n++;        stack[0] = 0;        long long ans = 0;        deep[0] = 0;        int top = 1;        for (int i = 1; i <= n; i++)        {            int depth = i;            while (A[i] < stack[top-1])            {                long long tmp = (long long)(i - deep[top-1]) * (long long)stack[top-1];                if (tmp > ans) ans = tmp;                depth = deep[top-1];                top --;            }            if (A[i] > stack[top-1])            {                stack[top] = A[i];                deep[top] = depth;                top ++;            }        }        printf("%lld\n", ans);    }    return 0;}
0 0
原创粉丝点击