题目链接:http://poj.org/problem?id=2082
求连续区域矩形最大面积(堆栈)
1 遇到比栈顶高度高或等于的矩形就进栈
2如果比栈顶高度低就让栈里比curh高的出栈。同时进行数据处理,刚开始时toweight = 0,cursize = 0,每出一个矩形就加上所出矩形的宽度,更新最大值;然后toweight + curw,curh的矩形进栈;
3最后栈中就是高度不下降矩形,如2 中的处理,不断更新最大值。
本题的关键就是如何更新最大值,有种追逐法的意思,大致就是不断求出当前栈中大于当前矩形那一段的所有后缀组成的面积,然后这段的宽度加上当前矩形的宽度,高为当前矩形的高,将组成的新矩形压入栈中。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <stack>
#include <map>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct Point {
int h;
int w;
};
int main()
{
//freopen("input.txt","r", stdin);
int n;
while(cin >> n && n != -1) {
stack<Point> s;
int w, h;
int mmax = 0;
int toheight = 0;//前高度
int toweight, cursize;//后缀宽度,后缀面积
Point t;
for(int i = 1; i <= n; i++) {
scanf("%d%d", &w, &h);
if(h >= toheight) {//第一种情况
t.h= h;
t.w= w;
s.push(t);
}
else{
cursize= toweight = 0;
while(!s.empty()) {
t= s.top();
if(t.h > h) {//第二种情况
toweight += t.w;
cursize = toweight * t.h;
if(cursize > mmax) mmax = cursize;
s.pop();
}
else break;
}
toweight += w;
t.h = h;
t.w = toweight;
s.push(t);
}
toheight = h;
}
toweight= cursize = 0;//第三步
while(!s.empty()) {
t= s.top();
toweight += t.w;
cursize = toweight * t.h;
if(cursize > mmax) mmax = cursize;
s.pop();
}
printf("%d\n",mmax);
}
return 0;
}