1.数组模拟栈
int stk[N], tt = 0;
void add(int x) {
stk[++tt] = x;
}
void remove() {
tt--;
}
2.单调栈(常见题型:找出每个数左/右边离它最近的比它大/小的数)
int a[N], n;
int f[i];
int s[N], tt = 0;
for (int i = 1; i <= n; i++) {
for (int i = 1; i <= n; i++) {
while (tt && a[s[tt]] <= a[i]) tt--;
f[i] = tt == 0 ? 0 : s[tt];
s[++tt] = a[i];
}
}
3.数组模拟队列
int q[N], hh = 0, tt = -1;
void push(int x) {
q[++tt] = x;
}
void pop() {
hh++;
}
int top() {
return q[hh];
}
bool empty() {
return hh > tt;
}
4.循环队列
int q[N], hh = 0, tt = 0;
void push(int x) {
q[tt++] = x;
if (tt == N) tt = 0;
}
void pop() {
hh++;
if (hh == N) hh = 0;
}
int top() {
return q[hh];
}
bool empty() {
return hh == tt;
}
5.单调队列(常见题型:滑动窗口的最大/小值)
int a[N];
int q[N], hh = 1, tt = 0;
for (int i = 1; i <= n; i++) {
scanf("%d", a + i);
while (hh <= tt && q[hh] < i - k + 1) hh++;
while (hh <= tt && a[q[tt]] > a[i]) tt--;
q[++tt] = i;
if (i >= k) printf("%d ", a[q[hh]]);
}
for (int i = 1; i <= n; i++) {
while (hh <= tt && q[hh] < i - k + 1) hh++;
while (hh <= tt && a[q[tt]] < a[i]) tt--;
q[++tt] = i;
if (i >= k) printf("%d ", a[q[hh]]);
}