1.单调栈的应用模板
给定一个长度为N的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出-1。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int stk[N],tt;
int main()
{
int n;
cin>>n;
while(n--)
{
int x;
cin>>x;
while(tt && stk[tt]>=x) //核心逻辑语句
tt--;
if(!tt)
printf("-1 ");
else
printf("%d ",stk[tt]);
stk[++tt]=x;
}
return 0;
}
2.单调对列应用模板:滑动窗口
给定一个大小为n≤106
的数组。
有一个大小为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
您的任务是确定滑动窗口位于每个位置时,窗口中的最大值和最小值。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
int a[N],q[N];
int main()
{
int n,k;
cin>>n>>k;
for(int i=0;i<n;i++)
cin>>a[i];
int hh=0,tt=0;
for(int i=0;i<n;i++)
{
//i - k + 1是以i为右端点、长度为k的区间的左端点,
//如果q[hh]的值比左端点小,那就说明队头节点已经不在区间中了,需要弹出。
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=0;
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]]);
}
return 0;
}