手写栈的模版题
样例分析
-
从尾部入栈
-
输出当前数列所有后缀最大值的下标的按位异或和
如图可知,栈单调递增,里面存储的都是后缀最大值
步骤如下
- 创建一个栈
- 在栈不为空的情况下,新来一个元素,把栈之中比新来元素小的全部清空
- 新元素入栈
清空复杂且慢,手写栈 直接清空
Ac Code
#include<bits/stdc++.h>
#define int unsigned long long
using namespace std;
const int N=1e6+7;
int n;
int a[N];
int stk[N],top=0;
int ans=0;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
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;
} 2.U514895 ١١(❛ᴗ❛)【单调栈】-左侧第一个较小值(不重复)
要求输出每一个位置 左侧小于 的第一个元素的下标
栈单调递减
如图
出栈的时候,我们发现右侧比出栈元素小的第一个元素就是新加入的元素
左侧比栈顶小的第一个元素,就是栈顶的下一个元素
Ac Code
#include<bits/stdc++.h>
//本题有-1的情况,不能用unsigned long long
//#define int unsigned long long
using namespace std;
const int N=1e6+7;
int n;
int a[N];
//注意stk存储的是下标
int stk[N],top=0;
int pre[N];//用来存储前缀
int ans=0;
signed 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[stk[top]]>a[i]){
//只有一个元素,找不到
if(top==1){
pre[stk[top]]=-1;
}
else{
pre[stk[top]]=stk[top-1];//存入元素下标
}
top--;//删除元素
}
stk[++top]=i;
}
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;
} 3.U514949 ١١(❛ᴗ❛)【单调栈】-左右两侧第一小于值(存在重复情况)
跟上题类似,只是要输出左右两侧第一个比其小的元素的下标,且有重复情况
相等情况对单调栈的影响
如果将相等的入栈,所以导致左侧答案出现了小于等于的情况
如果把相等的出栈,会影响右侧答案变成查找右侧第一个小于等于的情况
所以只能分开遍历,且记得清空栈
Ac Code
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+10;
int n;
int stk[N],a[N];
int l[N],r[N];
int top=0;
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[stk[top]]>=a[i]){
if(top==1){
l[stk[top]]=-1;
}
else {
l[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]){
//找到第n+1个,说明找不到了
if(i==n+1){
r[stk[top]]=-1;
}
else {
r[stk[top]]=i;
}
top--;
}
stk[++top]=i;
}
for(int i=1;i<=n;i++){
//本题会卡endl,需要用\n
cout<<l[i]<<' '<<r[i]<<'\n';
}
return 0;
}4.U514939 ١١(❛ᴗ❛)【单调栈】-左右两侧第一小于等于值(存在重复情况)
跟上题基本一样,只需要改变循环条件
Ac Code
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+10;
int n;
int stk[N],a[N];
int l[N],r[N];
int top=0;
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[stk[top]]>a[i]){
if(top==1){
l[stk[top]]=-1;
}
else {
l[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){
r[stk[top]]=-1;
}
else {
r[stk[top]]=i;
}
top--;
}
stk[++top]=i;
}
for(int i=1;i<=n;i++){
cout<<l[i]<<' '<<r[i]<<'\n';
}
return 0;
}



