当前位置: 首页 > news >正文

【斤斤计较的小Z——KMP / hash】

题目

KMP代码

#include <bits/stdc++.h>
using namespace std;const int N = 1e6+10;char s[N], p[N];
int nex[N];int main()
{cin >> p+1 >> s+1;int n = strlen(s+1);int m = strlen(p+1);//思路也是一致的,只要in > 0,就尝试拯救,最后补充一次匹配,如果不行就是0,如果行就是其它for(int i = 2, j = 0; i <= m; i++){while(j && p[j+1] != p[i]) j = nex[j];if(p[j+1] == p[i]) j++; //要么nex成功,要么j=0(此时也有可能匹配)nex[i] = j;}int cnt = 0;for(int i = 1, j = 0; i <= n; i++){while(j && p[j+1] != s[i]) j = nex[j];if(p[j+1] == s[i]) j++;if(j == m){j = 0;cnt++;}}cout << cnt;
}

hash代码

#include <bits/stdc++.h>
using namespace std;
using ll = long long;const int N = 1e6+10;
char s1[N], s2[N];const int base = 233;
const int mod = 1e9+7;ll f[N], qp[N];ll get_hash(int l, int r)
{ll ret = (f[r] - f[l-1] * qp[r-l+1] % mod + mod) % mod;return ret;
}
int main()
{cin >> s1+1 >> s2+1;int m = strlen(s1+1);int n = strlen(s2+1);qp[0] = 1;for(int i = 1; i <= n; i++){qp[i] = qp[i-1] * base % mod;f[i] = f[i-1] * base % mod + s2[i];f[i] %= mod;}ll hash1 = 0;for(int i = 1; i <= m; i++){hash1 = hash1 * base % mod + s1[i];hash1 %= mod;}int cnt = 0;for(int i = 1; i + m - 1 <= n; i++){int l = i, r = i+m-1;if(get_hash(l, r) == hash1) cnt++;}cout << cnt;
}

相关文章:

  • 【IQA技术专题】图像质量评价IQA技术和应用综述(万字长文!!)
  • 【20】番茄叶片病害数据集(有v5/v8模型)/YOLO番茄叶片病害检测
  • 嵌入式系统内核镜像相关(三)
  • 【普及/提高−】P1025 ——[NOIP 2001 提高组] 数的划分
  • C++实现数学功能
  • 2024年12月6级第二套第一篇
  • c++中main函数执行完后还执行其它语句吗?
  • Web APIS Day04
  • VOSK 离线中文语音识别实战:精准转文字、格式避坑全解析
  • 分类数据集 - 植物分类数据集下载
  • MySQL面试题(含答案),从简单到深入
  • 【全志V821_FoxPi】2-1 首次编译Tina5.0 SDK
  • 获取RadioButton的text,更换textview的text
  • 如何防止任务在多个项目中重复执行
  • Android SDK Manager 2025镜像,亲测好用
  • 蓝凌EKP产品:低门槛、可扩展、可视化公式引擎应用示例
  • 【系统介绍】IBMS智能建筑集成管理平台-智能化子系统的大脑
  • Gartner<Reference Architecture Brief: Data Integration>学习心得
  • RTX4060安装cuda12.3 cudnn8.9
  • Chrome 优质插件计划
  • 备案怎么关闭网站吗/cnzz
  • 学做吃的的网站/关键词可以分为哪三类
  • 小说网站怎么建设的/5118网站如何使用免费版
  • 深圳网站制作易捷网络/台州网站建设推广
  • 做风水起名网站推广/百度账号登录入口官网
  • 网站关键词多长/衡阳seo排名