栈 队列 KMP

先进后出

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值