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

来源:互联网 发布:迈克尔乔丹生涯数据 编辑:程序博客网 时间:2024/05/20 17:40

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

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

思路:因为考虑到n的大小为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 0