题目
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.
如下图所示,在一条水平线上方有若干个矩形,求包含于这些矩形的并集内部的最大矩形的面积(在下图中,答案就是阴影部分的面积),矩形个数<=10^5。
题解
多组数据
记得开long long+输出用%lld!!
用一个单调递增栈保存矩形高度,若加入的矩形高度小于栈顶高度,就弹出栈顶元素,累计弹出的矩形宽度,与每个弹出的矩形自身高度相乘更新答案,直到有矩形高度大于加入的矩形或栈空了,最后将加入的矩形与已经弹出的矩形合并成高度为加入矩形高度、宽度为累计宽度+1的矩形
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,p;
long long ans;
int a[100005],b[100005];
int main(){
scanf("%d",&n);
while (n){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
ans=p=0;
n++;
while (n--){
int x;
if (n==0) x=0; else
scanf("%d",&x);
if (a[p]<x){
a[++p]=x;b[p]=1;
} else{
int i=0;
while (p&&a[p]>=x){
i+=b[p];
ans=max(ans,(long long)a[p]*i);
p--;
}
a[++p]=x;b[p]=i+1;
}
}
printf("%lld\n",ans);
scanf("%d",&n);
}
}