单调栈进阶

· · 个人记录

U514906 ١١(❛ᴗ❛)【单调栈】-子数组最小值

如果在区间 l ,r 中, a 是最小值,那么区间内所有的数都要大于 a ,可以向左右两边找第一个小于 a 的数,那么从 a 往左到第一个小于 a 的点的所有点都可以作为起点,往右到第一个小于 a 的点都可以作为终点,最后区间的数量是 *起点数量终点数量**。

求左右两侧第一个小于的值,使用单调栈。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=200001;
ll n,a[maxn],s[maxn],top,l[maxn],r[maxn];
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    a[n+1]=-1;
    for(int i=1;i<=n+1;i++){
        while(top>0&&a[s[top]]>a[i]){
            l[s[top]]=s[top-1];
            r[s[top]]=i;
            top--;
        }
        s[++top]=i;
    }

    ll ans=0;
    for(int i=1;i<=n;i++){
        ll L=i-l[i],R=r[i]-i;
        ll lr=L*R*a[i];
        ans+=lr;
    }
    cout<<ans;
    return 0;
}

P6503 [COCI 2010/2011 #3] DIFERENCIJA

与上一题类似,求区间内最大值-最小值,使用两个单调栈,一个找最小值,一个找最大值。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=300005;
ll n,a[maxn],l[maxn],r[maxn],top,s[maxn],s1[maxn],l1[maxn],r1[maxn];
ll ans;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    a[n+1]=-1;
    for(int i=1;i<=n+1;i++){
        while(top>0&&a[s[top]]>=a[i]){
            l[s[top]]=s[top-1];
            r[s[top]]=i;
            top--;
        }
        s[++top]=i;
    }
    top=0;
    a[n+1]=1e9; 
    for(int i=1;i<=n+1;i++){
        while(top>0&&a[s[top]]<a[i]){
            l1[s[top]]=s[top-1];
            r1[s[top]]=i;
            top--;
        }
        s[++top]=i;
    }
    for(int i=1;i<=n;i++){
        ans=ans-(i-l[i])*(r[i]-i)*a[i];
        ans=ans+(i-l1[i])*(r1[i]-i)*a[i];
    }
    cout<<ans;
    return 0;
}