跳到正文

个人记录

单调栈进阶总结

the133lvlone约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月14日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 4 分钟

版本

  1. v1当前

总结

T1

C++
#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;
}
php
从每一个点出发,找把它当最小值的部分。

T2

C++
#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;
}
php
与T1同理,注意有相等的数字,但不影响计算方式,因为算的只是最小值

T3

C++
#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;
}
php
前面比a[k]小的值的点用r数组存,比自己大的用l存,只能跳到l[k],l[l[k]]...点处且不可超过r[k]
原文