您的位置:首页 > 其它

51nod-【1102 面积最大的矩形】

2016-11-29 12:00 267 查看
1102 面积最大的矩形


基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题


收藏


关注

有一个正整数的数组,化为直方图,求此直方图包含的最大矩形面积。例如 2,1,5,6,2,3,对应的直方图如下:



面积最大的矩形为5,6组成的宽度为2的矩形,面积为10。

Input
第1行:1个数N,表示数组的长度(0 <= N <= 50000)
第2 - N + 1行:数组元素A[i]。(1 <= A[i] <= 10^9)


Output
输出最大的矩形面积


Input示例
6
2
1
5
6
2
3


Output示例

10

和poj的2082是一类题目,其实我们对于每一个小的矩形,

它的最大面积就是这个小矩形能向左右延伸的最大长度,

那肯定是左边第一个小于它的和右边第一个小于它的

我们用到一个栈,(栈按照高度从小到大顺序,假设每一个小矩形的

宽度为1);对于当先小矩形的高度小于栈顶小矩形的高度,那么我们

就可以计算出在这其中的小矩形的面积的最大值,一直出栈,直到

栈顶小矩形的高度小于当前小矩形的高度为止

#include<cstdio>
#include<stack>
using namespace std;
typedef long long LL;
struct rec
{
LL w,h;
}a;
int main()
{
int n;
scanf("%d",&n);
LL ans=0,toph=0;
stack<rec>sta;
while(n--)
{
scanf("%lld",&a.h);
a.w=1;
if(a.h>=toph)
sta.push(a);
else
{
LL tempw=0,temps=0;
while(!sta.empty()&&sta.top().h>a.h)
{
tempw+=sta.top().w;
temps=sta.top().h*tempw;
if(temps>ans)
ans=temps;
sta.pop();
}
a.w+=tempw;
sta.push(a);
}
toph=a.h;
}
LL total=0,temps=0;
while(!sta.empty())
{
total+=sta.top().w;
temps=total*sta.top().h;
if(temps>ans)
ans=temps;
sta.pop();
}
printf("%lld\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: