F02【模板】字符串哈希
#include <iostream>
using namespace std;
typedef unsigned long long ULL;
const int N = 1000010, P = 131;
int n, m;
char s[N];
// p[i]=P^i, h[i]=s[1~i]的hash值
ULL p[N], h[N];
// 预处理 hash函数的前缀和
void init(){
p[0] = 1, h[0] = 0;
for(int i = 1; i <= n; i ++){
p[i] = p[i-1]*P;
h[i] = h[i-1]*P+s[i];
}
}
// 计算s[l~r]的 hash值
ULL get(int l, int r){
return h[r]-h[l-1]*p[r-l+1];
}
// 判断两子串是否相同
bool substr(int l1,int r1,int l2,int r2){
return get(l1, r1) == get(l2, r2);
}
int main(){
cin >> n >> m;
scanf("%s", s + 1);
init();
while(m --){
int a, b, c, d;
cin >> a >> b >>c >> d;
if(substr(a,b,c,d)) puts("Yes");
else puts("No");
}
return 0;
}
Luogu P3370【模板】字符串哈希
#include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N = 10010; int n, m; char s[N]; typedef unsigned long long ULL; const int P = 131; ULL h[N], ans[N]; // 计算串的哈希值 ULL calc(char *s, int n){ h[0] = 0; for(int i = 1; i <= n; i ++){ h[i] = h[i-1]*P+s[i]; } return h[n]; } int main(){ cin >> n; for(int i=1; i<=n; i++){ scanf("%s", s + 1); int m = strlen(s+1); ans[i] = calc(s, m); } sort(ans+1, ans+n+1); int cnt = 0; for(int i=1; i<=n; i++) if(ans[i]!=ans[i-1]) ++cnt; printf("%d", cnt); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!