单调栈进阶总结
xgc88888888
·
·
个人记录
1.U514906 ١١(❛ᴗ❛)【单调栈】-子数组最小值
题目要求求出以下结果:
\sum_{l = 1}^{N} \sum_{r = l}^{N}\ min(a_l,a_{l+1},…,a_r)
$\sum_{i = 1}^{n} \ a $即为 $a[i]$ 之和($for(i=1;i<=n;i++)sum+=a[i]$)
性质一:
$$
\sum_{i = 1}^{n} \ (a_i + b_i) = \sum_{i = 1}^{n} \ a_i+\sum_{i = 1}^{n} \ b_i
$$
性质二:
$$
\sum_{i = 1}^{n} \ a_ik = k\sum_{i = 1}^{n} \ a_i
$$
**二维公式推导**
性质一:
$$
\sum_{i = 1}^{n} \sum_{j = 1}^{n}\ (a_{ij} \pm b_{ij}) = \sum_{i = 1}^{n} \sum_{j = 1}^{n}\ a_{ij} \pm \sum_{i = 1}^{n} \sum_{j = 1}^{n}\ b_{ij}
$$
性质二:
$$
\sum_{i = 1}^{n} \sum_{j = 1}^{n}\ a_{ij}k = k\sum_{i = 1}^{n} \sum_{j = 1}^{n}\ a_{ij}
$$
性质三:
$$
\sum_{i = 1}^{n} \sum_{j = 1}^{n}\ a_{ij} = \sum_{j = 1}^{n}\sum_{i = 1}^{n} \ a_{ij}
$$
**补充**
$$
\sum_{i = 1}^{n} \ i = (1+2+3+…n) = \frac{n(n+1)}{2}
$$
$$
\sum_{i = 1}^{n} \ i^2 = (1^2+2^2+3^2+…n^2) = \frac{n(n+1)(2n+1)}{6}
$$
**Ac Code**
```cpp
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=5e5+10;
int n;
int a[N];
int stk[N],top=0;
int l[N],r[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]){
r[stk[top]]=i;//找右侧第一个最小的
l[stk[top]]=stk[top-1];//找左侧第一个最小的
top--;//弹出
}
stk[++top]=i;//入栈
}
for(int i=1;i<=n;i++){
//思路详见上课的某张图
ans+=a[i]*(r[i]-i)*(i-l[i]);//左侧从i到l[i],中间是a[i],右侧从i到r[i],相乘再相加即可得到答案
}
cout<<ans;
return 0;
}
```
---
2.[**P6503 [COCI 2010/2011 #3] DIFERENCIJA**](https://www.luogu.com.cn/problem/P6503)
与上题类似,但需要找最大值,且有重复的情况
**Ac Code**
```cpp
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=3e5+10;
int n;
int a[N];
int stk[N];
int top=0;
int l[N],r[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]){
r[stk[top]]=i;
l[stk[top]]=stk[top-1];
top--;
}
stk[++top]=i;
}
//去重时求最小值和最大值需要分开跑与如何去重,详见昨天总结
top=0;//清空
a[n+1]=INT_MAX;//哨兵变为最大值
for(int i=1;i<=n;i++){
ans-=a[i]*(r[i]-i)*(i-l[i]);//公式与上题一致,由题意得,要减去最小值,加上最大值
}
for(int i=1;i<=n+1;i++){
while(top>0&&a[stk[top]]<a[i]){
r[stk[top]]=i;
l[stk[top]]=stk[top-1];
top--;
}
stk[++top]=i;
}
for(int i=1;i<=n;i++){
ans+=a[i]*(r[i]-i)*(i-l[i]);
}
cout<<ans;
return 0;
}
```