跳到正文

个人记录

单调栈总结

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

文章信息

发布
2025年7月13日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 5 分钟

版本

  1. v1当前

总结

T1

C++
#include<bits/stdc++.h>
#define con continue
#define int unsigned long long
//#define double long double
using namespace std;
int a[1000002],b,s[1000002],t,k;
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>b;
	for(int i=1;i<=b;i++)
	{
		cin>>a[i];
		k^=i;
		while(t&&(a[s[t]]<a[i]))
		{
			k^=s[t--];
		}
		s[++t]=i;
		cout<<k<<endl;
	}
	return 0;
}
php
单调栈:有单调性可用,要维护其中的单调性

T2

C++
#include<bits/stdc++.h>
#define con continue
//#define int unsigned long long
//#define double long double
using namespace std;
int a[500003],b,s[500003],t,k,l[500003];
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>b;
	a[b+1]=-1;
	for(int i=1;i<=b;i++)
	{
		cin>>a[i];
	}
	for(int i=1;i<=b+1;i++)
	{
		while(t&&(a[s[t]]>a[i]))
		{
			if(t>1)
			{
				l[s[t]]=s[t-1];
			}
			else
			{
				l[s[t]]=-1;
			}
			t--;
		}
		s[++t]=i;
	}
	if(b>1000)
	{
		for(int i=2;i<=b;i++)
		{
			k^=l[i];
		}
		cout<<k;
	}
	else
	{
		for(int i=1;i<=b;i++)
		{
			cout<<l[i]<<' ';
		}
	}
	return 0;
}

T3

C++
#include<bits/stdc++.h>
#define con continue
//#define int unsigned long long
//#define double long double
using namespace std;
int a[500003],b,s[500003],t,k,l[500003],r[500003];
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>b;
	a[b+1]=-1;
	for(int i=1;i<=b;i++)
	{
		cin>>a[i];
	}
	for(int i=1;i<=b+1;i++)
	{
		while(t&&(a[s[t]]>=a[i]))
		{
			if(t>1)
			{
				l[s[t]]=s[t-1];
			}
			else
			{
				l[s[t]]=-1;
			}
			t--;
		}
		s[++t]=i;
	}
	t=0;
	for(int i=1;i<=b+1;i++)
	{
		while(t&&(a[s[t]]>a[i]))
		{
			if(i<=b)
			{
				r[s[t]]=i;
			}
			else
			{
				r[s[t]]=-1;
			}
			t--;
		}
		s[++t]=i;
	}
	for(int i=1;i<=b;i++)
	{
		cout<<l[i]<<' '<<r[i]<<endl;
	}
	return 0;
}

T4

C++
#include<bits/stdc++.h>
#define con continue
//#define int unsigned long long
//#define double long double
using namespace std;
int a[500003],b,s[500003],t,k,l[500003],r[500003];
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>b;
	a[b+1]=-1;
	for(int i=1;i<=b;i++)
	{
		cin>>a[i];
	}
	for(int i=1;i<=b+1;i++)
	{
		while(t&&(a[s[t]]>a[i]))
		{
			if(t>1)
			{
				l[s[t]]=s[t-1];
			}
			else
			{
				l[s[t]]=-1;
			}
			t--;
		}
		s[++t]=i;
	}
	t=0;
	for(int i=1;i<=b+1;i++)
	{
		while(t&&(a[s[t]]>=a[i]))
		{
			if(i<=b)
			{
				r[s[t]]=i;
			}
			else
			{
				r[s[t]]=-1;
			}
			t--;
		}
		s[++t]=i;
	}
	for(int i=1;i<=b;i++)
	{
		cout<<l[i]<<' '<<r[i]<<'\n';
	}
	return 0;
}
原文