跳到正文

个人记录

7.12单调栈学习

kamikuQAQ约 6 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

单调栈

顾名思义,可以将栈内元素按从小到大或者从大到小排列,优点是可以维护单调性
当元素符合单调性时入栈,然后在新元素破坏了单调性时弹出元素,使其能够继续维护单调性
出栈元素的右侧第一个 = 当前入栈元素
出栈元素的左侧第一个 = 栈中下一个元素

B3666

模版题,一直和栈顶元素异或运算就行

C++
#include<bits/stdc++.h>
using namespace std;
#define int unsigned long long
const int maxn = 1e6+7;
int a[maxn],stk[maxn];
int top=0;
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin>>n;
	int ans=0;
	for(int i=1;i<=n;i++) {
		cin>>a[i];
		ans^=i;
		while(top>0&&a[stk[top]]<=a[i]) {
			ans^=stk[top];
			top--;
		}
		stk[++top]=i;
		cout<<ans<<endl;
	}
	return 0;
}

١١(❛ᴗ❛)【单调栈】-左侧第一个较小值(不重复)

其实就多了一个在记录栈顶元素,然后在栈只有一个元素时记录为-1,但由于此题似乎1000以下的可以直接暴力骗(?)注意在到了边界的时候我们可以在原数组前后加极大、小值来清空栈

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e5+7;
int a[maxn],stk[maxn];
int pre[maxn];
int top;
int main() {
	int n;
	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[stk[top]]>a[i]) {
			if(top==1) {
				pre[stk[top]]=-1;
			} else {
				pre[stk[top]]=stk[top-1];
			}
			top--;
		}
		stk[++top]=i;
	}
	int ans=0;
	if(n>1000) {
		for(int i=2;i<=n;i++) {
			ans^=pre[i];
		}
		cout<<ans;
	} else {
		for(int i=1;i<=n;i++) {
			cout<<pre[i]<<' ';
		}
	}
	return 0;
}

١١(❛ᴗ❛)【单调栈】-左右两侧第一小于值(存在重复情况)١١(❛ᴗ❛)【单调栈】-左右两侧第一小于等于值(存在重复情况)

两题比较类似就一起讲了 其实也是固定模版,注意判右边界时右侧小于的下标就是入栈的下标,然后入栈条件不同,分别计算就行

T1

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e5+7;
int a[maxn],stk[maxn];
int pre1[maxn],pre2[maxn];
int top,top2;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin>>n;
	for(int i=1;i<=n;i++) {
		cin>>a[i];
	}
	a[0]=INT_MAX;
	a[n+1]=-1;
	for(int i=1;i<=n+1;i++) {
		while(top>0&&a[stk[top]]>=a[i]) {
			if(top==1) {
				pre1[stk[top]]=-1;
			} else {
				pre1[stk[top]]=stk[top-1];
			}
			top--;
		}
		stk[++top]=i;
	}
	top=0;
	for(int i=1;i<=n+1;i++) {
		while(top>0&&a[stk[top]]>a[i]) {
			if(i==n+1) {
				pre2[stk[top]]=-1;
			} else {
				pre2[stk[top]]=i;
			}
			top--;
		}
		stk[++top]=i;
	}
	int ans=0;
	for(int i=1;i<=n;i++) {
		cout<<pre1[i]<<' '<<pre2[i]<<'\n';
	}
	return 0;
}

T2

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e5+7;
int a[maxn],stk[maxn];
int pre1[maxn],pre2[maxn];
int top,top2;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin>>n;
	for(int i=1;i<=n;i++) {
		cin>>a[i];
	}
	a[0]=INT_MAX;
	a[n+1]=-1;
	for(int i=1;i<=n+1;i++) {
		while(top>0&&a[stk[top]]>a[i]) {
			if(top==1) {
				pre1[stk[top]]=-1;
			} else {
				pre1[stk[top]]=stk[top-1];
			}
			top--;
		}
		stk[++top]=i;
	}
	top=0;
	for(int i=1;i<=n+1;i++) {
		while(top>0&&a[stk[top]]>=a[i]) {
			if(i==n+1) {
				pre2[stk[top]]=-1;
			} else {
				pre2[stk[top]]=i;
			}
			top--;
		}
		stk[++top]=i;
	}
	int ans=0;
	for(int i=1;i<=n;i++) {
		cout<<pre1[i]<<' '<<pre2[i]<<'\n';
	}
	return 0;
}
原文