【poj2559】Largest Rectangle in a Histogram
2016-02-14 09:51
459 查看
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:![](http://poj.org/images/2559_1.jpg)
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 n, denoting the number of rectangles it is composed of. You may assume that 1<=n<=100000. Then follow n integers h1,...,hn, where0<=hi<=1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. 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 3 4 1000 1000 1000 1000 0
Sample Output
8 4000
Hint
Huge input, scanf is recommended.Source
Ulm Local 2003/* 维护一个栈中元素(高度)单调递增的栈 扫描每个矩形,若比栈顶元素高就直接进栈 否则弹出栈顶,直至递增,弹栈过程中累计弹出元素的宽度和,每弹出一个就用弹出高度*累计宽度更新答案。 最后给当前矩形的宽度加上累计宽度,入栈。 扫描结束后,依次弹出栈顶元素,按相同方法更新答案,直至栈为空 */ #include<cstdio> #include<iostream> using namespace std; long long h[100010]; struct node { long long hei,wid; }stack[100010]; int n,head=0; long long widsum=0,ans=0; int main() { while (scanf("%d",&n) && n) { ans=0; head=0; stack[head].hei=-1; for (int i=1;i<=n;i++) scanf("%lld",&h[i]); h[++n]=0; for (int i=1;i<=n;i++) { if (h[i]>=stack[head].hei)//大于栈顶元素,直接入栈 { stack[++head].hei=h[i]; stack[head].wid=1; } else { widsum=0; while (stack[head].hei>h[i])//不断弹出栈顶元素 直至递增 { widsum+=stack[head--].wid; ans=max(ans,stack[head+1].hei*widsum);//用弹出高度*累计宽度更新答案 } stack[++head].hei=h[i]; stack[head].wid=widsum+1;//给当前矩形的宽度加上累计宽度入栈 } } printf("%lld\n",ans); } }
相关文章推荐
- python动态网页爬取——四六级成绩批量爬取
- 喝下一罐可口可乐后的反应
- 搭建hexo博客
- 在uboot里面加入环境变量使用run来运行
- MyBatis
- web项目从域名申请到发布
- SQL Server 插入数据后获得自增主键值
- Python在Console下显示文本进度条的方法
- Draw Picture With Python Matplotlib
- 测试
- 软件开发流程
- Adafruit的樹莓派教程第一課福利:做一個備份鏡像
- android开发游记:APP自动更新功能的快速集成和实现方法讲解
- [小技巧] Windows 下如何识别没有扩展名的文件
- 【python笔记】python中的list、tuple、set、dict用法简析
- listView布局中按钮点击事件放到activity或者fragment中响应
- 跟陈皓一起学makefile
- java web 项目如何部署到互联网中 通过输入域名访问?
- RecyclerView与ListView的异同
- 極客范 – GeekFan.net | Adafruit的樹莓派教程第一課:為你的樹莓派准備一張SD卡 - 極客范 - GeekFan.net 极客范 – GeekFan.net 首頁 科技資訊 硬件