栈
数组模拟栈
# include <iostream>
using namespace std;
const int N= 100010 ;
int stk[ N] , tt;
stk[ ++ tt] = x;
tt-- ;
if ( tt> 0 ) not empty
else empty
stk[ tt] ;
单调栈
acwing 830.单调栈
# include <iostream>
# include <cstdio>
using namespace std;
const int N= 100010 ;
int n;
int stk[ N] , tt;
int main ( )
{
scanf ( "%d" , & n) ;
for ( int i= 0 ; i< n; i++ )
{
int x;
cin>> x;
while ( tt&& stk[ tt] >= x) tt-- ;
if ( tt) printf ( "%d " , stk[ tt] ) ;
else printf ( "-1 " ) ;
stk[ ++ tt] = x;
}
return 0 ;
}
队列
数组模拟队列
# include <iostream>
using namespace std;
const int N= 100010 ;
int q[ N] , hh, tt= - 1 ;
q[ ++ tt] = x;
hh++ ;
if ( hh<= tt) not empty
else empty
stk[ tt] ;
q[ hh]
单调队列
acwing 154.滑动窗口
# include <iostream>
# include <cstdio>
using namespace std;
const int N= 100010 ;
int n, k;
int a[ N] , q[ N] ;
int main ( )
{
scanf ( "%d%d" , & n, & k) ;
for ( int i= 0 ; i< n; i++ ) scanf ( "%d" , & a[ i] ) ;
int hh= 0 , tt= - 1 ;
for ( int i= 0 ; i< n; i++ )
{
if ( hh<= tt&& i- k+ 1 > q[ hh] ) hh++ ;
while ( hh<= tt&& a[ q[ tt] ] >= a[ i] ) tt-- ;
q[ ++ tt] = i;
if ( i>= k- 1 ) printf ( "%d " , a[ q[ hh] ] ) ;
}
puts ( "" ) ;
hh= 0 , tt= - 1 ;
for ( int i= 0 ; i< n; i++ )
{
if ( hh<= tt&& i- k+ 1 > q[ hh] ) hh++ ;
while ( hh<= tt&& a[ q[ tt] ] <= a[ i] ) tt-- ;
q[ ++ tt] = i;
if ( i>= k- 1 ) printf ( "%d " , a[ q[ hh] ] ) ;
}
puts ( "" ) ;
return 0 ;
}