单调栈
基础
1,什么是单调栈,顾名思义,是单调递增或单调递减的栈
2,为啥会有单调性,因为我们可以将栈变成单调的
3,单调栈有啥用处,用来维护某数左右第一个大于或小于的数
说了跟没说一样,重新来
就拿求一个数左边第一个比他小的数来举例,如果暴力,就是两重循环枚举,从i到1枚举第一个比他小的数,但是这样太慢了,因此我们可以用一个栈来代替暴力,每一次从栈中弹出一个个数,直到找到比i小的数,在弹出过程中,已经弹出的数一定不会有用了吗,答案是肯定的,因为i比被弹出的数小,且在被弹出的数的右边,如果这个被弹出的数之后被作为左边的最小数,那么i一定比它更优,因此反证出被弹出的数之后一定不会作为最小数,我们可以将它弹出
这题是让我们求每一次的后缀最大值异或和(一个比它后面任意数都大的数)
如果一个后插入的数比这个数大,这个数就可以从栈中弹出
代码:
C++ 复制 #include <bits/stdc++.h>
#define int unsigned long long
using namespace std ;
const int N= 1 e 6 + 10 ;
int a[N];
int stk[N];
int top;
signed main (){
ios ::sync_with_stdio (0 );
cin.tie (0 ),cout.tie (0 );
int n;
cin>> n;
for (int i= 1 ;i<= n;i++ ) cin>> a[i];
int s1= 0 ;
for (int i= 1 ;i<= n;i++ ){
s1^= i;
while (top> 0 && a[stk[top]]<= a[i]) s1^= stk[top],top-- ;
stk[++ top]= i;
cout<< s1<< endl;
}
return 0 ;
}
这题是板子,直接上代码
代码:
C++ 复制 #include <bits/stdc++.h>
#define int long long
using namespace std ;
const int N= 5 e 5 + 10 ;
int a[N];
int stk[N];
int top;
signed main (){
int n;
cin>> n;
for (int i= 1 ;i<= n;i++ ) cin>> a[i];
int s1= 0 ;
for (int i= 1 ;i<= n;i++ ){
while (top> 0 && a[stk[top]]>= a[i]) top-- ;
if (n> 1000 ){
if (top> 0 ) s1^= stk[top];
else if (i!= 1 ) s1^=- 1 ;
}
else {
if (top== 0 ) cout<< "-1 " ;
else cout<< stk[top]<< " " ;
}
stk[++ top]= i;
}
if (n> 1000 ) cout<< s1<< " " ;
return 0 ;
}
这题是一样的只是要跑两个栈就可以过,如果大于等于弹出栈
代码:
C++ 复制 #include <bits/stdc++.h>
#define int long long
using namespace std ;
const int N= 5 e 5 + 10 ;
int a[N];
int stk1[N],stk2[N],t1[N],t2[N];
int top1,top2;
signed main (){
int n;
cin>> n;
for (int i= 1 ;i<= n;i++ ) scanf (" %d " ,& a[i]);
int s1= 0 ;
for (int i= 1 ;i<= n;i++ ){
while (top1> 0 && a[stk1[top1]]>= a[i]) top1-- ;
if (top1== 0 ) t1[i]=- 1 ;
else t1[i]= stk1[top1];
stk1[++ top1]= i;
}
for (int i= n;i>= 1 ;i-- ){
while (top2> 0 && a[stk2[top2]]>= a[i]) top2-- ;
if (top2== 0 ) t2[i]=- 1 ;
else t2[i]= stk2[top2];
stk2[++ top2]= i;
}
for (int i= 1 ;i<= n;i++ ) printf (" %d %d\n " ,t1[i],t2[i]);
return 0 ;
}
这题类似上题,跑两个栈,如果大于弹出栈
代码:
C++ 复制 #include <bits/stdc++.h>
#define int long long
using namespace std ;
const int N= 5 e 5 + 10 ;
int a[N];
int stk1[N],stk2[N],t1[N],t2[N];
int top1,top2;
signed main (){
int n;
cin>> n;
for (int i= 1 ;i<= n;i++ ) scanf (" %d " ,& a[i]);
int s1= 0 ;
for (int i= 1 ;i<= n;i++ ){
while (top1> 0 && a[stk1[top1]]> a[i]) top1-- ;
if (top1== 0 ) t1[i]=- 1 ;
else t1[i]= stk1[top1];
stk1[++ top1]= i;
}
for (int i= n;i>= 1 ;i-- ){
while (top2> 0 && a[stk2[top2]]> a[i]) top2-- ;
if (top2== 0 ) t2[i]=- 1 ;
else t2[i]= stk2[top2];
stk2[++ top2]= i;
}
for (int i= 1 ;i<= n;i++ ) printf (" %d %d\n " ,t1[i],t2[i]);
return 0 ;
}