0
点赞
收藏
分享

微信扫一扫

hdu1506 Largest Rectangle in a Histogram--DP/栈


原题链接: ​​ http://acm.hdu.edu.cn/showproblem.php?pid=1506​​


一:原题内容


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:

hdu1506 Largest Rectangle in a Histogram--DP/栈_#include


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, where 0 <= 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



二:分析理

利用stack来做,其实利用了压缩的思想,每个push进栈的值都是相较于前一个进栈的较小值。

三:AC代码

#include<iostream>  
#include<stack>
#include<string.h>
#include<algorithm>

using namespace std;

long long int heights[100005];//64位

int main()
{
int n;
while (scanf("%d", &n) && n)
{
for (int i = 0; i < n; i++)
scanf("%I64d", &heights[i]);//64位

stack<int> s;
long long int ans = 0;//64位

for (int i = 0; i < n; i++)
{
if (s.empty() || heights[i]>heights[s.top()])
s.push(i);
else
{
int cur = s.top();
s.pop();
long long int width = s.empty() ? i : i - s.top() - 1;
ans = max(ans, width*heights[cur]);

i--;//!!!
}
}

while (!s.empty())
{
int cur = s.top();
s.pop();
long long int width = s.empty() ? n : n - s.top() - 1;
ans = max(ans, width*heights[cur]);
}

printf("%I64d\n", ans);//64位的输出,坑
}

return 0;
}









举报

相关推荐

0 条评论