poj2559(单调栈)

传送门

 

写法一:

#include<bits/stdc++.h>
#define per(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
typedef long long ll;
//#define int long long
const ll inf =2333333333333333LL;
const double eps=1e-8;
int read(){
    char ch=getchar();
    int res=0,f=0;
    while(ch<'0' || ch>'9'){f=(ch=='-'?-1:1);ch=getchar();}
    while(ch>='0'&&ch<='9'){res=res*10+(ch-'0');ch=getchar();}
    return res*f;
}
// ------------------------head
#define mod 1000000007
const int N=100005;
int n,a[N],top,L[N],R[N];
ll res=0;
stack<int>st;

signed main()
{
    while(~scanf("%d",&n)&&n!=0){
        while(!st.empty())st.pop();
        res=0;
        per(i,1,n)scanf("%d",&a[i]);
        per(i,1,n){
            while(!st.empty()&&a[i]<=a[st.top()])st.pop();
            if(st.empty())L[i]=0;
            else L[i]=st.top();
            st.push(i);
        }
        while(!st.empty())st.pop();
        for(int i=n;i>0;i--){
            while(!st.empty()&&a[i]<=a[st.top()])st.pop();
            if(st.empty())R[i]=n;
            else R[i]=st.top()-1;
            st.push(i);
        }
        per(i,1,n){
            res=max(res,(ll)a[i]*(R[i]-L[i]));
        }
        printf("%lld\n",res);
    }

    return 0;
}
View Code

 

写法二:

#include<bits/stdc++.h>
#define per(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
typedef long long ll;
//#define int long long
const ll inf =2333333333333333LL;
const double eps=1e-8;
int read(){
    char ch=getchar();
    int res=0,f=0;
    while(ch<'0' || ch>'9'){f=(ch=='-'?-1:1);ch=getchar();}
    while(ch>='0'&&ch<='9'){res=res*10+(ch-'0');ch=getchar();}
    return res*f;
}
// ------------------------head
#define mod 1000000007
const int N=100005;
int n,a[N],top;
ll res=0;
stack<int>st;

signed main()
{
    while(~scanf("%d",&n)&&n!=0){
        while(!st.empty())st.pop();
        res=0;
        per(i,1,n)scanf("%d",&a[i]);
        a[n+1]=-1;
        for(int i=1;i<=n+1;i++){
            if(st.empty()||a[i]>=a[st.top()])st.push(i);
            else{
                while(!st.empty()&&a[i]<a[st.top()]){
                    top=st.top();st.pop();
                    res=max(res,(ll)a[top]*(i-top));
                }
                st.push(top);
                a[top]=a[i];
            }
        }
        printf("%lld\n",res);
    }

    return 0;
}
View Code

 

posted @ 2018-09-22 00:23  WindFreedom  阅读(157)  评论(0编辑  收藏  举报