目录
模拟栈
模板
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int skt[N],tt=0;
void push(int x){
skt[++tt]=x;
}
void pop(){
tt--;
}
bool empty(){
return tt==0;
}
int query(){
return skt[tt];
}
int main(){
int n;
cin>>n;
while(n--){
string s;
int x;
cin>>s;
if(s=="push"){
cin>>x;
push(x);
}
if(s=="pop"){
pop();
}if(s=="empty"){
if(empty())cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
if(s=="query"){
cout<<query()<<endl;
}
}
return 0;
}
单调栈
栈内具有单调性
模板
//常见模型:找出每个数左边离它最近的比它大/小的数
int tt = 0;
for (int i = 1; i <= n; i ++ )
{
while (tt && check(stk[tt], i)) tt -- ;
stk[ ++ tt] = i;
}
实践
单调栈题意
给定一个长度为 N 的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出 −1。
输入格式
第一行包含整数 N,表示数列长度。
第二行包含 N 个整数,表示整数数列。
输出格式
共一行,包含 N 个整数,其中第 i 个数表示第 i 个数的左边第一个比它小的数,如果不存在则输出 −1。
数据范围
1≤N≤10^5
1≤数列中元素≤10^9
输入样例:
5
3 4 2 7 5
输出样例:
-1 3 -1 2 2
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int skt[N],tt=0,a[N];//栈存的下标
void push(int x){
skt[++tt]=x;
}
void pop(){
tt--;
}
bool empty(){
return tt==0;
}
int query(){
return skt[tt];
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
for(int i=1;i<=n;i++){
while(!empty()&&a[skt[tt]]>=a[i]){
pop();
}
if(empty())cout<<"-1"<<' ';
else cout<<a[skt[tt]]<<' ';
push(i);
}
return 0;
}
模拟队列
模板
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int q[N],hh=0,tt=-1;
void push(int x){
q[++tt]=x;
}
void pop(){
hh++;
}
bool empty(){
return hh>tt;
}
int query(){
return q[hh];
}
int main(){
int n;
cin>>n;
while(n--){
string s;
int x;
cin>>s;
if(s=="push"){
cin>>x;
push(x);
}
if(s=="pop"){
pop();
}if(s=="empty"){
if(empty())cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
if(s=="query"){
cout<<query()<<endl;
}
}
return 0;
}
单调队列
模板
//常见模型:找出滑动窗口中的最大值/最小值
int hh = 0, tt = -1;
for (int i = 0; i < n; i ++ )
{
while (hh <= tt && check_out(q[hh])) hh ++ ; // 判断队头是否滑出窗口
while (hh <= tt && check(q[tt], i)) tt -- ;
q[ ++ tt] = i;
}
实践
滑动窗口题意
给定一个大小为 n≤10^6 的数组。
有一个大小为 k 的滑动窗口,它从数组的最左边移动到最右边。
你只能在窗口中看到 k 个数字。
每次滑动窗口向右移动一个位置。
以下是一个例子:
该数组为
[1 3 -1 -3 5 3 6 7]
,k 为 3。
窗口位置 | 最小值 | 最大值 |
---|---|---|
[1 3 -1] -3 5 3 6 7 | -1 | 3 |
1 [3 -1 -3] 5 3 6 7 | -3 | 3 |
1 3 [-1 -3 5] 3 6 7 | -3 | 5 |
1 3 -1 [-3 5 3] 6 7 | -3 | 5 |
1 3 -1 -3 [5 3 6] 7 | 3 | 6 |
1 3 -1 -3 5 [3 6 7] | 3 | 7 |
你的任务是确定滑动窗口位于每个位置时,窗口中的最大值和最小值。
输入格式
输入包含两行。
第一行包含两个整数 n 和 k,分别代表数组长度和滑动窗口的长度。
第二行有 n 个整数,代表数组的具体数值。
同行数据之间用空格隔开。
输出格式
输出包含两个。
第一行输出,从左至右,每个位置滑动窗口中的最小值。
第二行输出,从左至右,每个位置滑动窗口中的最大值。
输入样例:
8 3
1 3 -1 -3 5 3 6 7
输出样例:
-1 -3 -3 -3 3 3
3 3 5 5 6 7
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
int a[N],q[N],hh=0,tt=-1;//队列存的下标
int main(){
int n,k;
cin>>n>>k;
for(int i=1;i<=n;i++)cin>>a[i];
for(int i=1;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>=1)cout<<a[q[hh]]<<' ';
}
cout<<endl;
hh=0,tt=-1;
for(int i=1;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>=1)cout<<a[q[hh]]<<' ';
}
cout<<endl;
return 0;
}