【题目描述】
51Nod - 1215 数组的宽度(单调栈)

【思路】
单调栈处理左右第一处比自己小和大的位置,然后计算每个元素对答案的贡献,注意若干相同元素不能重复计算,所以在处理左边第一处大于自己的位置后,右边就要处理第一处大于等于自己的位置,这样才不会重复计算,比自己小的位置也同理

#include<stack>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int maxn=50005;

int n;
int a[maxn];
int Lmin[maxn],Rmin[maxn],Lmax[maxn],Rmax[maxn];
stack<int> st;

int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;++i) scanf("%d",&a[i]);
    while(st.size()) st.pop();
    for(int i=1;i<=n;++i){
        while(st.size() && a[st.top()]>=a[i]) st.pop();
        if(st.empty()) Lmin[i]=0;
        else Lmin[i]=st.top();
        st.push(i);
    }
    while(st.size()) st.pop();
    for(int i=1;i<=n;++i){
        while(st.size() && a[st.top()]<=a[i]) st.pop();
        if(st.empty()) Lmax[i]=0;
        else Lmax[i]=st.top();
        st.push(i);
    }
    while(st.size()) st.pop();
    for(int i=n;i>=1;--i){
        while(st.size() && a[st.top()]>a[i]) st.pop();
        if(st.empty()) Rmin[i]=n+1;
        else Rmin[i]=st.top();
        st.push(i);
    }
    while(st.size()) st.pop();
    for(int i=n;i>=1;--i){
        while(st.size() && a[st.top()]<a[i]) st.pop();
        if(st.empty()) Rmax[i]=n+1;
        else Rmax[i]=st.top();
        st.push(i);
    }
    long long ans=0;
    for(int i=1;i<=n;++i){
        ans+=(long long)(i-Lmax[i])*(Rmax[i]-i)*a[i];
        ans-=(long long)(i-Lmin[i])*(Rmin[i]-i)*a[i];
    }
    printf("%lld\n",ans);
    return 0;
}

相关文章:

  • 2022-01-28
  • 2021-06-19
  • 2022-01-07
  • 2022-01-26
  • 2021-09-26
  • 2021-06-08
  • 2021-10-31
  • 2022-12-23
猜你喜欢
  • 2021-07-29
  • 2021-08-06
  • 2022-02-18
  • 2022-12-23
  • 2021-09-28
  • 2021-07-01
  • 2021-11-15
相关资源
相似解决方案