Flexible and practical application stack - histogram largest rectangular area

Histogram largest rectangular area

This is a stack of application questions which facilitates in-depth understanding of the principles and functions of the stack, each memory element index, encountered small to trigger a stack began to turn left, when the count of the count to the far right, on the realization a. Note that the number and length of the stack there are now incremental, and finally how to deal with, understand the operational mechanism

A histogram is composed of many rectangles, asked to identify the largest rectangular area in a given histogram. The histogram does not exceed the number of assumed rectangle 1000.

All the width of the rectangle are assumed as one unit. Histogram shown below in seven rectangular, the height respectively 6,2,5,4,5,1,6, wherein successive rectangles can be composed of a rectangular area of ​​the maximum 12.

Histogram .jpg

Achieve Tip: Consider using a stack to resolve this problem.

Input formats:

The first line of the input rectangle number histogram. A second set of histograms of input line height, with each height interval spaces.

Output formats:

The maximum area rectangle rectangle can continuously output thereof.

Sample input:

Here we are given a set of inputs. E.g:

7
6 2 5 4 5 1 6

Sample output:

Given here corresponding output. E.g:

12

AC Code

#include<iostream>
#include<cstdio>
#include<stack>
#include<cmath>
using namespace std;
int main()
{
    int maxs=0,i,h[1010],n,t;
    stack <int> s;
    cin>>n;
    for (i=0;i<=n-1;i++)
      scanf("%d",&h[i]);
    i=0;
    while (i<=n-1)
    {
        if (s.empty() or h[s.top()]<=h[i])
          s.push(i++);
        else
        {
            t=s.top();
            s.pop();
            maxs=max(maxs,h[t]*(s.empty() ? i : (i-s.top()-1)));//触发的i和次峰值之间的(峰值左面都是比他高的,不在栈里,已经出栈、处理过,栈里面存的是地址)长度,空就说明都是比他大的
        }
    }
    while (!s.empty())
    {
        t=s.top();
        s.pop();
        maxs=max(maxs,h[t]*(s.empty() ? i : (i-s.top()-1)));
    }   
    cout<<maxs;
    return 0;
}

Guess you like

Origin www.cnblogs.com/IamIron-Man/p/11956822.html