单调栈总结
the133lvlone · · 个人记录
总结
T1
#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;
}
单调栈:有单调性可用,要维护其中的单调性
T2
#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
#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
#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;
}