3.7 周六晚上—单调栈1
P5788 【模板】单调栈
数组初始化为 。
这是一个单调递增的栈,求右侧的元素。用一个 while 来枚举比 小的元素。找到了就把栈顶出栈,出栈的元素 值是 。
#include<bits/stdc++.h>
using namespace std;
const int N=3e6+10;
int a[N],n,f[N];
stack<int>st;
int main(){
cin>>n;
for(int i=1;i<=n;++i){
cin>>a[i];
while(st.size()&&a[i]>a[st.top()]){
f[st.top()]=i;
st.pop();
}
st.push(i);
}
for(int i=1;i<=n;++i){
cout<<f[i]<<" ";
}
return 0;
}U514895 ١١(❛ᴗ❛)【单调栈】-左侧第一个较小值(不重复)
这道题跟上一题不同的是求左侧的元素,所以 for 循环是倒着遍历的。而且是小于 ,所以得把 > 改成 <。因为输出量过大,所以当 时得用 全部 ^ 上所有答案,最后输出 。
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=3e6+10;
int a[N],n,f[N];
stack<int>st;
bool vis=false;
signed main(){
cin>>n;
for(int i=1;i<=n;++i){
cin>>a[i];
}
for(int i=n;i>=1;--i){
while(st.size()&&a[i]<a[st.top()]){
f[st.top()]=i;
st.pop();
}
st.push(i);
}
if(n>1000){
int ans=f[1];
for(int i=2;i<=n;++i){
if(f[i]==0)f[i]=-1;
ans^=f[i];
}
cout<<ans<<"\n";
}
else{
for(int i=1;i<=n;++i){
if(f[i]==0)f[i]=-1;
cout<<f[i]<<" ";
}
}
return 0;
}P12241 [蓝桥杯 2023 国 C] 最大区间
假设 是这个区间最小的数
初始化
初始化为 ,
初始化为 。
先预处理出 和 数组。
求右侧第一个比 更小的数,
求左侧第一个比 更小的数。
最后把每个 的 算出来,取 max。
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=3e5+10;
int a[N],n,f1[N],f2[N],ans;
stack<int>st1,st2;
signed main(){
cin>>n;
for(int i=1;i<=n;++i){
cin>>a[i];
f2[i]=n+1;
}
for(int i=1;i<=n;++i){
while(st1.size()&&a[st1.top()]>a[i]){
f2[st1.top()]=i;
st1.pop();
}
st1.push(i);
}
for(int i=n;i>=1;--i){
while(st2.size()&&a[st2.top()]>a[i]){
f1[st2.top()]=i;
st2.pop();
}
st2.push(i);
}
for(int i=1;i<=n;++i){
int l=f1[i];
int r=f2[i];
ans=max(ans,(r-l-1)*a[i]);
}
cout<<ans<<"\n";
return 0;
}