AcWing histogram largest rectangle

AcWing histogram largest rectangle

topic:

  • There are pictures. Turn link

answer:

  • Monotonous stack.
  • OI two years before going to school to learn this road classic question ... ...
  • Every practice is a plain rectangle with a high current is high, then to the left and right to find the first highly than their own small rectangle (that is found around the border), then the answer is current the current height of the rectangle * (the right found border - find the left edge + 1). The final answer is to take the max current in all the answers inside.
  • Complexity of O (n ^ 2), the problem lies in expanding the boundaries of this step. You may be thinking this way, if the current height of the rectangle <= a rectangle in front, then a rectangle in front of me can simply delete it, because the next time to find the first time a rectangle smaller than a certain height, will certainly find the current rectangle will not find in front of a rectangle.
  • Further to just abstract ideas, it is the following process:
    1. Build a stack
    2. For the current rectangle, as long as the stack top> = height of the current rectangle, to pop out until the top <current height of the rectangle. So is the current position of the top rectangle of the left edge of the rectangle are looking for.
    3. Insert the current rectangle
  • So look for the right border of empathy.

  • So that each rectangle only be accessed again, the complexity is O (n), very good!

#include <iostream>
#include <cstdio>
#include <stack>
#define N 100005
#define inf 0x7fffffff
#define int long long
using namespace std;

struct Node {int val, pos;};
int n, ans;
int a[N], l[N], r[N];

int read()
{
    int x = 0; char c = getchar();
    while(c < '0' || c > '9') c = getchar();
    while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
    return x;
}

signed main()
{
    while(scanf("%lld", &n) == 1)
    {
        if(!n) break;
        stack<Node> stk1; stk1.push((Node){-inf, 0});
        for(int i = 1; i <= n; i++) a[i] = read();
        for(int i = 1; i <= n; i++)
        {
            while(stk1.top().val >= a[i]) stk1.pop();
            l[i] = stk1.top().pos + 1;
            stk1.push((Node){a[i], i});
        }
        stack<Node> stk2; stk2.push((Node){-inf, n + 1});
        for(int i = n; i >= 1; i--)
        {
            while(stk2.top().val >= a[i]) stk2.pop();
            r[i] = stk2.top().pos - 1;
            stk2.push((Node){a[i], i});
        }
        ans = -inf;
        for(int i = 1; i <= n; i++) ans = max(ans, a[i] * (r[i] - l[i] + 1));
        printf("%lld\n", ans);
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/BigYellowDog/p/11300755.html