Poj 2082 Terrible Sets 【堆栈】
http://poj.org/problem?id=2082
堆栈是一种先进后出的数据结构。他有一个栈顶指针,通过对堆栈的入站和出栈控制,可以改变一个序列的顺序。
题目大意:紧贴x轴有一些互相挨着的矩形,给定每个矩形的长宽,问它们可以形成的最大矩形是多少。
用堆栈来实现,将矩形入栈,保持栈中的元素高度递增,如果即将入栈的高度data.h比栈顶元素的高度lasth小,则退栈。一直退到可以保持栈顶元素高度递增的那个元素x,在退栈过程中统计由lasth至x之间可以形成的最大矩形面积S,记录由lasth至x之间矩形总宽度totalw,在弹出这些元素之后再向栈中压入一个高度为data.h,宽度为totalw+data.w的矩形,然后继续读入下一个矩形。最后栈中元素一定是高度递增的,扫描一遍即可。
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> #include <cmath> #include <queue> #include <stack> using namespace std; template <class T> void checkmin(T &t,T x) {if(x < t) t = x;} template <class T> void checkmax(T &t,T x) {if(x > t) t = x;} template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;} template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;} typedef pair <int,int> PII; typedef pair <double,double> PDD; typedef long long ll; #define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++) struct rec { int w , h; } data; int main() { int n,ans,i,lasth,totalw,curarea; while(~scanf("%d",&n) && n!=-1) { ans = 0; stack <rec> s; lasth = 0; for(i=0;i<n;i++) { scanf("%d%d",&data.w,&data.h); if(data.h >= lasth) { s.push(data); } else { totalw = 0; //总宽 curarea = 0; //当前面积 while(!s.empty() && s.top().h > data.h) { totalw += s.top().w; curarea = totalw * s.top().h; checkmax(ans , curarea); s.pop(); } totalw += data.w; data.w = totalw; s.push(data); } lasth = data.h; } totalw = 0; curarea = 0; while(!s.empty()) { totalw += s.top().w; curarea = totalw * s.top().h; checkmax(ans , curarea); s.pop(); } printf("%d\n" , ans); } return 0; }