题意:给出n个矩形的长和宽,它们挨着排列在x轴上,求能够构成的最大矩形的面积。
思路:多个矩阵拼起来的矩形最大高度取决于最短的那个小矩形,使用两次单调栈处理出每个小矩形左右两个方向上最近的一个比这个矩形矮的矩形的位置, 即确定了当前矩形能向左右两边延伸的最远距离。然后按照矩形的高度从低到高,算出来每个矩形高度能得到的最大面积,取最大值即可。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = 1000000007;
const int maxn = 50005;
const int N = 100005;
struct node{
int h,w,l,r,pos;
/*矩形的高、宽、向左的边界、向右的边界、初始下标*/
bool operator < (const node &b) const{
return h < b.h;
}
}rec[maxn];
int len[maxn];
int main(){
int n,ddStack[maxn];
while(~scanf("%d",&n) && n != -1){
len[0] = 0;
for(int i=0; i<n; ++i){
scanf("%d%d", &rec[i].w, &rec[i].h);
rec[i].l = 0;
rec[i].r = n;
rec[i].pos = i;
len[i + 1] = len[i] + rec[i].w;
}
/*两次单调栈维护左右两个方向*/
int pos = 0;
for(int i=0; i<n; ++i){
if(pos == 0 || rec[i].h >= rec[ddStack[pos - 1]].h){
ddStack[pos++] = rec[i].pos;
} else {
while(pos >= 1 && rec[ddStack[pos - 1]].h > rec[i].h){
rec[ddStack[pos - 1]].r = i;
--pos;
}
ddStack[pos++] = rec[i].pos;
}
}
pos = 0;
for(int i=n-1; i>=0; --i){
if(pos == 0 || rec[i].h >= rec[ddStack[pos - 1]].h){
ddStack[pos++] = rec[i].pos;
} else {
while(pos >= 1 && rec[ddStack[pos - 1]].h > rec[i].h){
rec[ddStack[pos - 1]].l = i + 1;
--pos;
}
ddStack[pos++] = rec[i].pos;
}
}
sort(rec, rec + n);
int ans = 0, now = 0;
for(int i=0; i<n; ++i){
now = rec[i].h * (len[rec[i].r] - len[rec[i].l]);
if(now > ans)ans = now;
}
printf("%d\n",ans);
}
return 0;
}