POJ2082 Terrible Sets(单调栈)

题意:给出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;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值