1. 程式人生 > >poj2796(單調棧)

poj2796(單調棧)

can ack eof nbsp sig etc read std %d

傳送門

實測如果有多個值相等,輸出最後一個最大值的LR

ac代碼:

#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,L[N],R[N]; ll s[N],a[N]; stack<ll>st; signed main() {
while(scanf("%d",&n)!=EOF){ s[0]=0; while(!st.empty())st.pop(); per(i,1,n){scanf("%lld",&a[i]);s[i]=s[i-1]+a[i];} for(int i=1;i<=n;i++){ while(!st.empty()&&a[st.top()]>=a[i])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>=1;i--){ while(!st.empty()&&a[st.top()]>=a[i])st.pop(); if(st.empty())R[i]=n; else R[i]=st.top()-1; st.push(i); } ll res=0; int k; per(i,1,n){ ll tmp=(ll)a[i]*(s[R[i]]-s[L[i]]); if(tmp>=res){ res=tmp; k=i; } } printf("%lld\n%d %d\n",res,L[k]+1,R[k]); } return 0; }

poj2796(單調棧)