http://poj.org/problem?id=2082
题意:
紧贴x轴有一些相邻的矩形,给定每个矩形的长和宽,问他们可以形成的最大矩形是多少。
思路:
用栈来做,栈内元素保持递增;
将所有矩形分成块状进行操作,更新。
如果即将入栈的高度da.h比栈顶元素小,则退栈。一直退到可以保持栈顶元素持续递增的哪个元素x,在退栈过程中统计当前cuearea,并对ans进行更新
在弹出这些元素后,向栈中压入一个宽为totalw+da.w,高为da.h的矩形,然后继续读入下一个矩形
由于栈中元素一直是递增的,再扫一遍栈即可。
代码:
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string> #include<iomanip> #include<algorithm> #include<string.h> #include<queue> #include<cmath> #include<stack> using namespace std; const int maxn=1e5+10; const int inf=1e10; typedef long long ll; struct rec { int w,h; }; rec da; int main() { int n; while(cin>>n&&n!=-1) { int ans=0,curarea=0; int lasth=0; int totalw=0; stack<rec> s; for(int i=0; i<n; i++) { cin>>da.w>>da.h; if(da.h>=lasth) s.push(da); else { totalw=0; while(!s.empty()&&s.top().h>da.h) { totalw+=s.top().w; curarea=totalw*s.top().h; ans=max(ans,curarea); s.pop(); } totalw+=da.w; da.w=totalw; s.push(da); } lasth=da.h; } curarea=0; totalw=0; while(!s.empty()) { totalw+=s.top().w; curarea=totalw*s.top().h; ans=max(ans,curarea); s.pop(); } printf("%d ",ans); } }