Sunday, 6 September 2015

Largest Rectangle in a Histogram (SPOJ HISTOGRA, POJ 2559, HDU 1506, ZOJ 1985)

///     Raihan Ruhin
///     CSE, Jahangirnagar University.
///     Dhaka-Bangladesh.
///     id: raihanruhin (topcoder / codeforces / codechef / uva / uvalive), 3235 (lightoj)
///     mail: raihanruhin@ (yahoo / gmail / facebook)
///     blog: ruhinraihan.blogspot.com

#include<bits/stdc++.h>
using namespace std;

#define SET(a) memset(a,-1,sizeof(a))
#define CLR(a) memset(a,0,sizeof(a))
#define PI acos(-1.0)

#define MOD 1000000007
#define MX 100005

long long hist[MX];
int lft[MX], rgt[MX];
void Histogram(int n)
{
    stack<long long>stk;
    stk.push(0);
    hist[0]=-1;

    for(int i=1;i<=n;i++)
    {
        while(hist[stk.top()]>=hist[i])
            stk.pop();
        lft[i]=  stk.top()+1;
        stk.push(i);
    }

    while(!stk.empty())
        stk.pop();

    stk.push(n+1);
    hist[n+1]=-1;
    for(int i=n;i>0;i--)
    {
        while(hist[stk.top()]>=hist[i])
            stk.pop();
        rgt[i]=  stk.top()-1;
        stk.push(i);
    }
return;
}


int main()
{
    //ios_base::sync_with_stdio(0);cin.tie(0);
    int tc, kk=1, n, m, x, y, a, b, c;
    string s;
    //cin>>tc;
    while(cin>>n && n)
    {
        for(int i=1;i<=n;i++)
            cin>>hist[i];
        Histogram(n);
        long long mx=0;
        for(int i=1;i<=n;i++)
            mx=max(mx, hist[i]*(long long)(rgt[i]-lft[i]+1));
            //cout<<hist[i]<<" "<<lft[i]<<" "<<rgt[i]<<endl;
        cout<< mx <<"\n";
    }
return 0;
}

No comments:

Post a Comment