Algorithm学习笔记 --- Largest Rectangle in a Histogram
来源:互联网 发布:adidas淘宝官方旗舰店 编辑:程序博客网 时间:2024/06/05 22:54
此题也是一道典型的单调队列例题,此题也可以用dp,搜索做,搜索和dp会简单一些。
Description
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
Output
Sample Input
7 2 1 4 5 1 3 34 1000 1000 1000 10000
Sample Output
84000
Hint
Source
解题分析:
此题提议大概是求解矩形中面积最大的矩形面积。
输入为:
首先是输入N个用例,然后依次输入每组数据,对应的输出N个用例对应的最大面积。
做法:这里用的是单调队列求解。
做法是设两个数组一个存储原数组的元素,另一个是存储一个(i,j)这个范围内的数,
i-1一定要比i小,j+1一定也要小于等于j。可能有多个范围,要求出最大的范围,然后用范围j-i的值,就是长度,然后乘以高度。求出面积。
代码:
#include<stdio.h>
#include<algorithm>
#define MAX_N 100009
using namespace std;
int rect[MAX_N];
struct seg
{
long long value,s;
}q[MAX_N];
int main()
{
int n ;
while(scanf("%d",&n)&&n)
{
long long area = 0 ,top = 0;
for(int i=0;i!=n;++i)
scanf("%d",rect+i);
for(int i=0;i!=n;++i)
{
//队列为空或者当前元素大于队尾时入队
if(!top || q[top-1].value < rect[i])
{
q[top].value = rect[i];
q[top++].s = i ;
}
//此时,右边界出现,需要做更新
else if(q[top-1].value>rect[i])
{
//如果有比最大值大的面积,则更新最大值
while(top && q[top-1].value>rect[i])
{
--top;
area = max(area,q[top].value*(i-q[top].s));
}
//队空
if(!top)
q[top++].value = rect[i] ;
else if(q[top-1].value < rect[i])
q[top++].value = rect[i] ;
}
}
//队中可能还有元素,也要做相应的更新
while(top)
{
--top;
area = max(area,q[top].value*(n-q[top].s));
}
printf("%lld\n",area);
}
return 0;
}
- Algorithm学习笔记 --- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram
- POJ 2559 Largest Rectangle in a Histogram 笔记
- POJ 2559 Largest Rectangle in a Histogram 单调栈学习
- Problem H: Largest Rectangle in a Histogram
- mysql 任务调度
- 动态背景下的运动目标检测
- BubbleSort
- ftk学习记(进度条篇)
- C语言中如何获得文件大小
- Algorithm学习笔记 --- Largest Rectangle in a Histogram
- 读《平凡的世界》有感
- Ubuntu 下编译 VLC-Win32
- red hat 未注册不能使用yum的解决办法
- [hdu-2048] 神、上帝以及老天爷
- 数学漫谈
- POI与JXL写Excel的性能对比
- FFMPEG结构体分析:AVFrame
- HDU 4527 小明系列故事——玩转十滴水