POJ 2559 最大矩形面积 Histogram

 1 #include <bits/stdc++.h>
 2 #define Maxn 100010
 3 using namespace std;
 4 //sta[]是单调栈,栈中存储的元素高度递增,p为栈的栈顶位置
 5 int h[Maxn],w[Maxn],n,sta[Maxn],p;//h:矩形的hight,w:矩形的width
 6 long long ans=0;
 7 int main()
 8 {
 9     freopen("data1.in","r",stdin);
10     while(scanf("%d",&n)!=EOF){
11         memset(w,0,sizeof(w));
12         for(int i=1; i<=n; ++i){scanf("%d",&h[i]);} //读入n个矩形的高度,每个矩形的默认宽度:1
13         sta[0]=h[n+1]=p=0;  //边界的处理:sta[0]=0为了方便第1个矩形入栈,h[n+1]=0为了将栈中所有矩形出栈
14         for(int i=1; i<=n+1; ++i){
15             if(sta[p]<h[i]){ //当前矩形比栈顶矩形高度高的话入栈,不要写=,h[0]=0,而h[n+1]也是0,是出栈用的
16                 sta[++p]=h[i];
17                 w[p]=1;
18             }else{
19                 int width=0;
20                 while(sta[p]>h[i]){//当前矩形比栈顶矩形高度低则出栈,不要写=,h[n+1]是0是出栈用的
21                     width+=w[p];
22                     ans=max(ans,(long long)width*sta[p]);
23                     p--;
24                 }
25                 sta[++p]=h[i],w[p]=width+1; //更新当前矩形宽带(与前面矩形构成的最大宽带,木桶的短板),同时将其入栈
26             }
27         }
28         printf("%lld\n",ans);
29     }
30     return 0;
31 }

 

posted @ 2018-06-09 09:30  lznoip  阅读(78)  评论(0)    收藏  举报