hdu 1506(单调栈实现)

来源:互联网 发布:淘宝助理 定时上架 编辑:程序博客网 时间:2024/05/21 06:38

#include <iostream>#include<stack>#include<cstdio>using namespace std;struct node{int w=1;long long h;}s[100005];int main(){int n;while(scanf("%d",&n)!=EOF&&n){int i;stack<node>st;for(i=0;i<n;i++){scanf("%lld",&s[i].h);s[i].w=1;//忘记重置为1导致错误}st.push(s[0]);long long total_w,cur_area,maxn=0;for(i=1;i<n;i++){if(s[i].h>=s[i-1].h)//维护栈的单调增{st.push(s[i]);}else{total_w=0,cur_area=0;while(!st.empty()&&s[i].h<st.top().h){total_w+=st.top().w;cur_area=total_w*st.top().h;//总宽*当前矩形的高度if(cur_area>maxn) maxn=cur_area;st.pop();//否则出栈}total_w+=s[i].w;//加上要进栈的矩形宽度s[i].w=total_w;//合并成新的矩形st.push(s[i]);}}total_w=0,cur_area=0;while(!st.empty()){total_w+=st.top().w;cur_area=total_w*st.top().h;if(cur_area>maxn) { maxn=cur_area;}st.pop();}printf("%lld\n",maxn);}return 0;}

0 0