跳到正文

个人记录

单调栈进阶

Me163_Comet约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月13日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 3 分钟

版本

  1. v1当前

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

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

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

C++
#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

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

C++
#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;
}
原文