单调栈进阶
Me163_Comet · · 个人记录
U514906 ١١(❛ᴗ❛)【单调栈】-子数组最小值
如果在区间
求左右两侧第一个小于的值,使用单调栈。
#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;
}