3.7 周六晚上--单调栈1

· · 个人记录

3.7 周六晚上--单调栈1

P5788 【模板】单调栈

这是一个单调递增的栈,求右侧的元素。用一个 ```while``` 来枚举比 $a_i$ 小的元素。找到了就把栈顶出栈,出栈的元素 $f$ 值是 $i$。 ```cpp #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 ١١(❛ᴗ❛)【单调栈】-左侧第一个较小值(不重复)](https://www.luogu.com.cn/problem/U514895?contestId=313591) 这道题跟上一题不同的是求左侧的元素,所以 ```for``` 循环是倒着遍历的。而且是小于 $a[i]$,所以得把 ```>``` 改成 ```<```。因为输出量过大,所以当 $n>1000$ 时得用 $ans$ 全部 ```^``` 上所有答案,最后输出 $ans$。 ```cpp #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] 最大区间](https://www.luogu.com.cn/problem/P12241?contestId=313591) 假设 $a_i$ 是这个区间最小的数 ### 初始化 > 1. $f1$ 初始化为 $0$, > > 2. $f2$ 初始化为 $n+1$。 先预处理出 $f1$ 和 $f2$ 数组。 求右侧第一个比 $a_i$ 更小的数, 求左侧第一个比 $a_i$ 更小的数。 最后把每个 $a_i$ 的 $(r-l+1)×min(a_l,a_l+1,...,a_r)$ 算出来,取 ```max```。 ```cpp #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; } ```