其他分享
首页 > 其他分享> > SP1805 HISTOGRA - Largest Rectangle in a Histogram(单调栈)

SP1805 HISTOGRA - Largest Rectangle in a Histogram(单调栈)

作者:互联网

SP1805 HISTOGRA - Largest Rectangle in a Histogram

解题思路:利用单调栈找到某个元素左右两边比这个元素小的下标,再用区间个数乘以最小值就可以了。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double lf;
typedef unsigned long long ull;
typedef pair<int,int>P;
const int inf = 0x7f7f7f7f;
const ll INF = 1e16;
const int N = 1e6+10;
const ull base = 131;
const ll mod =  1e9+7;


inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}
inline string readstring(){string str;char s=getchar();while(s==' '||s=='\n'||s=='\r'){s=getchar();}while(s!=' '&&s!='\n'&&s!='\r'){str+=s;s=getchar();}return str;}
int random(int n){return (int)(rand()*rand())%n;}
void writestring(string s){int n = s.size();for(int i = 0;i < n;i++){printf("%c",s[i]);}}
bool is_prime(int n){if(n <2) return false;for(int i = 2;i*i <= n;i++){if(n%i == 0) return false;}return true;}


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



void solve(int n){
    stack<int>st;
    memset(l,0,sizeof l);
    memset(r,0,sizeof r);
    a[n+1] = -1;
    for(int i = 1;i <= n+1;i++){
        while(st.size()&&a[i]<a[st.top()]){
            r[st.top()] = i;
            st.pop();
        }
        st.push(i);
    }
    while(st.size()) st.pop();
    for(int i = n;i >= 1;i--){
        while(st.size()&&a[i]<a[st.top()]){
            l[st.top()] = i;
            st.pop();
        }
        st.push(i);
    }
    /*
    for(int i = 1;i <= n;i++){
        printf("%d ",l[i]);
    }
    puts("");
    for(int i = 1;i <= n;i++){
        printf("%d ",r[i]);
    }
    */
    ll ans = 0;
    for(int i = 1;i <= n;i++){
        ans = max(ans,a[i]*(r[i]-l[i]-1ll));
    }
    cout<<ans<<endl;
}
int main(){
    //freopen("in.txt","r",stdin);
    int n;
    while(scanf("%d",&n)&&n){
        for(int i = 1;i <= n;i++){
            a[i] = read();
        }
        solve(n);
    }

    return 0;
}

标签:ch,return,int,st,HISTOGRA,while,Histogram,Rectangle,getchar
来源: https://blog.csdn.net/weixin_42868863/article/details/116354773