单调栈进阶总结
the133lvlone · · 个人记录
总结
T1
#include<bits/stdc++.h>
#define con continue
#define int long long
//#define double long double
using namespace std;
int r[500002],l[500002],b,s[500002],a[500002],t;
signed main()
{
cin>>b;
a[b+1]=-1;
for(int i=1;i<=b;i++)
{
scanf("%d",&a[i]);
}
for(int i=1;i<=b+1;i++)
{
while(t&&(a[s[t]]>a[i]))
{
l[s[t]]=s[t-1];
t--;
}
s[++t]=i;
}
t=0;
for(int i=1;i<=b+1;i++)
{
while(t&&(a[s[t]]>a[i]))
{
r[s[t]]=i;
t--;
}
s[++t]=i;
}
t=0;
for(int i=1;i<=b;i++)
{
t+=a[i]*(i-l[i])*(r[i]-i);
}
cout<<t;
return 0;
}
从每一个点出发,找把它当最小值的部分。
T2
#include<bits/stdc++.h>
#define con continue
#define int long long
//#define double long double
using namespace std;
int r[500002],l[500002],b,s[500002],a[500002],t,k;
signed main()
{
cin>>b;
a[b+1]=-1;
for(int i=1;i<=b;i++)
{
scanf("%d",&a[i]);
}
for(int i=1;i<=b+1;i++)
{
while(t&&(a[s[t]]>=a[i]))
{
l[s[t]]=s[t-1];
r[s[t]]=i;
t--;
}
s[++t]=i;
}
for(int i=1;i<=b;i++)
{
k-=a[i]*(i-l[i])*(r[i]-i);
}
t=0;
a[b+1]=1e8+1602;
for(int i=1;i<=b+1;i++)
{
while(t&&(a[s[t]]<a[i]))
{
l[s[t]]=s[t-1];
r[s[t]]=i;
t--;
}
s[++t]=i;
}
for(int i=1;i<=b;i++)
{
k+=a[i]*(i-l[i])*(r[i]-i);
}
cout<<k;
return 0;
}
与T1同理,注意有相等的数字,但不影响计算方式,因为算的只是最小值
T3
#include<bits/stdc++.h>
#define con continue
#define int long long
//#define double long double
using namespace std;
int r[500002],l[500002],b,s[500002],a[500002],t,k,n=1,m;
signed main()
{
cin>>b;
a[b+1]=-1;
for(int i=1;i<=b;i++)
{
scanf("%d",&a[i]);
}
for(int i=1;i<=b+1;i++)
{
while(t&&(a[s[t]]>a[i]))
{
r[s[t]]=i;
t--;
}
s[++t]=i;
}
t=0;
a[b+1]=1e9+1602;
for(int i=1;i<=b+1;i++)
{
while(t&&(a[s[t]]<=a[i]))
{
l[s[t]]=i;
t--;
}
s[++t]=i;
}
while(n<=b)
{
m=n;
while(l[m]<r[n])
{
m=l[m];
}
n=m+1;
k++;
}
cout<<k;
return 0;
}
前面比a[k]小的值的点用r数组存,比自己大的用l存,只能跳到l[k],l[l[k]]...点处且不可超过r[k]