poj2082 连续矩形最大面积

题目链接: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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值