题目链接:http://poj.org/problem?id=2559
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 24259 | Accepted: 7844 |
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 3 4 1000 1000 1000 1000 0
Sample Output
8 4000
Hint
Source
题解:
一开始想到的是;从当前元素,向前向后延伸,计算最多能延伸多长。O(n^2)超时~~~~~
然后看了网上的题解:单调栈。
如果当前元素大于栈顶元素,则入栈;否则,栈顶元素出栈,直到栈顶元素小于当前元素或栈为空为止。期间更新出栈元素能达到的宽度,因为上一次出栈的元素的高度必定大于这次出栈元素的高度,所以他对这次出栈元素的宽度有贡献,并更新ans。出栈完毕后,再将已出栈元素的总宽度叠加到当前元素中,因为这些元素的高度都大于等于当前元素的高度,所以这些元素对当前元素的宽度都有贡献。 最后栈中可能还会有元素,把他“倒”出来再统计就是了。
代码如下:
1 #include<cstdio>//poj2559 单调栈 此栈从栈底到栈顶为严格递增 2 #include<cstring> 3 #define MAX(a,b) (a>b?a:b) 4 #define LL long long 5 #define mod 1000000007 6 7 using namespace std; 8 9 struct Stack 10 { 11 int he; 12 int len; 13 }s[100010]; 14 15 int main() 16 { 17 int n,h; 18 while(scanf("%d",&n) && n) 19 { 20 LL ans = -1; 21 int top = 0;//从1开始存放,top指向栈顶元素 22 for(int i = 1; i<=n; i++) 23 { 24 scanf("%d",&h); 25 int len = 0; 26 //当栈顶元素的高度大于等于当前将入栈的元素的高度时,出栈,并更新其之前元素的宽度 27 while(top>0 && h<=s[top].he) 28 { 29 len += s[top].len; 30 ans = MAX(ans,1LL*s[top].he*len); 31 top--; 32 } 33 //更新入栈元素的宽度 34 s[++top].len = len + 1; 35 s[top].he = h; 36 } 37 38 int len = 0; 39 while(top>0)//将栈内剩余的元素“倒”出来统计 40 { 41 len += s[top].len; 42 ans = MAX(ans,1LL*len*s[top].he); 43 top--; 44 } 45 46 printf("%lld\n",ans); 47 } 48 return 0; 49 }