Largest Rectangle in a Histogram(单调栈)

Largest Rectangle in a Histogram 分享至QQ空间

时间限制(普通/Java):1000MS/10000MS     内存限制:65536KByte
总提交: 136            测试通过:65

描述

 

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.

输入

 

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.

输出

 

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.

样例输入

样例输出

题目来源

ULM 2003

解题思路: 找左边比其小的最右边的位置和右边比其小的最左边的位置  二次运用单调栈 从前往后维护一个单调递增的栈 从后往前维护一个单调递增的栈

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <map>
 6 #include <unordered_map>
 7 using namespace std;
 8 
 9 typedef long long ll;
10 const int N=100005;
11 int arr[N];
12 int sta[N];
13 int n,top;
14 ll maxx;
15 unordered_map<int,int> ma1,ma2;
16 
17 int main(){
18     ios::sync_with_stdio(false);
19     while(cin>>n&&n!=0){
20         for(int i=1;i<=n;i++) cin>>arr[i];
21         memset(sta,0,sizeof(sta));
22         top=0,maxx=0;
23         for(int i=1;i<=n;i++){
24             int flag=0;
25             while(arr[sta[top]]>=arr[i]&&top) top--,flag=1;
26             if(flag==0) ma1[i]=i-1;   //
27             else ma1[i]=top==0?0:sta[top];
28             sta[++top]=i; //存放的是位置
29         }
30         memset(sta,0,sizeof(sta));
31         top=0;
32         for(int i=n;i>=1;i--){
33             int flag=0;
34             while(arr[sta[top]]>=arr[i]&&top) top--,flag=1;
35             if(flag==0) ma2[i]=i+1;
36             else ma2[i]=top==0?n+1:sta[top];
37             sta[++top]=i;
38         }
39         for(int i=1;i<=n;i++){
40             maxx=max(maxx,1LL*(ma2[i]-ma1[i]-1)*arr[i]);
41         }
42         cout << maxx << endl;
43     }
44     return 0;
45 }
View Code

 

 

原文地址:https://www.cnblogs.com/qq-1585047819/p/11346741.html