Largest Rectangle in a Histogram (单调队列)

来源:互联网 发布:入侵学校数据库 编辑:程序博客网 时间:2024/05/27 01:32

Problem 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.

Input
The input contains several test cases. Each test case describes a histogram and starts with an integer <i>n</i>, denoting the number of rectangles it is composed of. You may assume that <i>1<=n<=100000</i>. Then follow <i>n</i> integers <i>h<sub>1</sub>,...,h<sub>n</sub></i>, where <i>0<=h<sub>i</sub><=1000000000</i>. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is <i>1</i>. A zero follows the input for the last test case.

Output
For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.

Sample Input
7 2 1 4 5 1 3 34 1000 1000 1000 10000

Sample Output
84000

题目大概:

又连续的矩形,宽都是1,高不同,求最大矩形。

思路:

单调队列。

有些数据要用long long。int过不了。

代码:

include <iostream>#include <cmath>#include <cstdio>#include <cstring>using namespace std;int n;long long a[100005];int l[100005];int r[100005];int q[100005];int getl(){    q[0]=0;    int le=0,ri=1;    for(int i=1;i<=n;i++)    {        while(le<ri&&a[i]<=a[q[ri-1]])ri--;        l[i]=i-q[ri-1]-1;        q[ri++]=i;    }}int getr(){   q[0]=n+1;    int le=0,ri=1;      for(int i=n;i>=1;i--)    {        while(le<ri&&a[i]<=a[q[ri-1]])ri--;        r[i]=q[ri-1]-i-1;        q[ri++]=i;    }}int main(){    while(scanf("%d",&n))    {if(n==0)break;    memset(a,0,sizeof(a));    memset(l,0,sizeof(l));    memset(r,0,sizeof(r));    memset(q,0,sizeof(q));    for(int i=1;i<=n;i++)    {        scanf("%d",&a[i]);    }    a[0]=a[n+1]=-1;    getl();    getr();   long long sun=-1;    for(int i=1;i<=n;i++)    {  long long sum=0;        sum=(l[i]+r[i]+1)*a[i];        if(sum>sun)sun=sum;    }    printf("%I64d\n",sun);    }    return 0;}




阅读全文
0 0
原创粉丝点击