HDU 1506 Largest Rectangle in a Histogram(单调队列)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1506

题意:有n个靠在一起的长方条,同底同宽不同高,如图左边,现在需要在其中找到一个面积最大的矩形。如图右边。
图片

思路:因为考虑到n的大小为 1 0 5 10^5 105,暴力去寻找肯定是不行的,但是可以从暴力的思想上去优化。对于每个位置i,考虑最后的矩形与当前的小矩形同高,那么得到左右延伸最大宽度即可。所以对于位置i,维护两个值,即向左最大延伸值l[i]和向右最大延伸值r[i](我包括了位置i,所以在计算面积时需要减一)。那么位置i的最大矩形面积为(l[i] + r[i] - 1) * a[i]

在求l数组和r数组的时候,也不可直接暴力去求,可利用单调队列维护。

代码如下:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <algorithm>
using namespace std;

const int N = (int)(1e5 + 5);

typedef pair<int, int> P;

int a[N], l[N], r[N];
int n;

struct Que {//单调队列维护
  P que[N];
  int head, tail;

  void init() {
    head = tail = 0;
  }

  int push(int c, int x, int i) {
    while (head < tail && x <= que[tail - 1].first) tail--;
    int t;
    if (head < tail)
      t = (c == 0 ? i - que[tail - 1].second : que[tail - 1].second - i);
    else
      t = (c == 0 ? i : n - i + 1);
    que[tail++] = P(x, i);
    return t;
  }

};

int main() {
  while (scanf("%d", &n) != EOF && n) {
    for (int i = 1; i <= n; i++)
      scanf("%d", &a[i]);
    Que q;
    q.init();
    for (int i = 1; i <= n; i++)
      l[i] = q.push(0, a[i], i);
    q.init();
    for (int i = n; i >= 1; i--)
      r[i] = q.push(1, a[i], i);
    long long ans = -1;
    for (int i = 1; i <= n; i++)
      ans = max(ans, (l[i] + r[i] - 1) * 1LL * a[i]);
    printf("%lld\n", ans);
  }
  return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值