栈
先进后出
int tt;
int st[N];
int x;
cin >> x;
//进栈
st[ ++ tt] = x;
//弹出
t --;
//输出栈顶元素
cout << st[tt] ;
//判空
if(tt > 0) not empty;
else empty;
830.单调栈
#include<iostream>
using namespace std;
const int N = 1010;
int n;
int T[N], tt;
int main()
{
cin >> n;
for(int i = 0; i < n; i ++)
{
int x;
cin >> x;
while(tt && T[tt] >= x) tt --;
if(tt) cout << T[tt] << endl;
else
cout << "-1" << " " << endl;
T[ ++ tt] = x;
}
return 0;
}
队列
先进先出
int hh = 0, tt = -1;
int T[N];
int x;
cin >> x;
//进队
T[ ++ tt] = x;
//弹出
h ++;
//判空
if(hh <= tt) not empty;
else empty;
滑动窗口(单调队列)
1.判断队头是否已经弹出窗口。
2.比较,插入队尾。
#include<iostream>
using namespace std;
const int N = 1010;
int n, k;
int W[N], a[N];
int main()
{
cin >> n >> k;
for(int i = 0; i < n ; i ++)
cin >> a[i];
int h = 0, t = -1;
for(int i = 0; i < n; i ++)
{
if(h <= t && i - k + 1 > W[h]) h ++;
while(h <= t && a[W[h]] >= a[i]) t --;
W[ ++ t] = i;
if(i >= k - 1) cout << a[W[h]] << " ";
}
return 0;
}
KMP算法
#include<iostream>
using namespace std;
const int N = 10010, M = 100010;
int n, m;
char p[N], s[M];
int ne[N];
int main()
{
cin >> n >> p + 1 >> m >> s + 1;
//求next的过程
for(int i = 2, j = 0; i <= n; i ++)
{
while(j && p[i] != p[j + 1]) j = ne[j];
if(p[i] == p[j + 1]) j ++;
ne[i] = j;
}
//kmp匹配过程
for(int i = 1, j = 0; i <= m; i ++)
{
while(j && s[i] != p[j + 1]) j = ne[j];
if(s[i] == p[j + 1]) j ++;
if(j == n)
{
printf("%d ", i - n + 1);
j = ne[j];
}
}
return 0;
}