题意:紧贴x轴有一些挨着的矩形,给出每个矩形的长宽,问能组成的最大矩形面积为多少
分析:用堆栈来维护高度递增的矩形,遇到高度小的,弹出顶部矩形直到符合递增,顺便计算矩形面积,且将弹出的宽度都累积到当前的矩形中,这样最后再扫描一遍,算面积很方便,这题应该算是 POJ 2559 的强化版了
收获:stack的应用,求矩形面积,矩阵相乘,表达式计算
代码:
/************************************************ * Author :Running_Time * Created Time :2015/9/9 星期三 13:50:48 * File Name :L.cpp ************************************************/ #include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 typedef long long ll; const int N = 5e4 + 10; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; struct M { int w, h; }m[N]; int main(void) { int n; while (scanf ("%d", &n) == 1) { if (n == -1) break; for (int i=1; i<=n; ++i) { scanf ("%d%d", &m[i].w, &m[i].h); } stack<M> S; int ans = 0, lasth = 0; for (int i=1; i<=n; ++i) { if (m[i].h >= lasth) { S.push (m[i]); lasth = m[i].h; } else { int totw = 0, area = 0; while (!S.empty () && S.top ().h > m[i].h) { totw += S.top ().w; area = totw * S.top ().h; if (area >= ans) ans = area; S.pop (); } m[i].w += totw; S.push (m[i]); lasth = m[i].h; } } int totw = 0, area = 0; while (!S.empty ()) { totw += S.top ().w; area = totw * S.top ().h; if (area >= ans) ans = area; S.pop (); } printf ("%d ", ans); } return 0; }