AcWing 841. 字符串哈希
原题链接
简单
作者:
不理葫芦
,
2024-01-10 09:56:26
,
所有人可见
,
阅读 24
- 公式:h[R]-h[L-1]*p[R-L+1];
- 应用场景:判断两个子串是否相等
- 使用substr速度过慢
- p取131,类型取unsigned long long
- 以字符串=“ABCDSESD”为例,h[0] = 0,h[3] = “ABC”的哈希值
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010,P = 131;
int n,m;
char str[N];
typedef unsigned long long ULL;
ULL h[N],p[N];
int get(int l,int r)
{
return h[r] - h[l-1] * p[r-l+1];
}
int main()
{
scanf("%d%d",&n,&m);
scanf("%s",str+1);
p[0] = 1;
for(int i = 1;i <= n;i++)
{
h[i] = h[i-1] * P +str[i];
p[i] = p[i-1] * P;
}
while(m--)
{
int l1,l2,r1,r2;
scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
if(get(l1,r1)==get(l2,r2))puts("Yes");
else puts("No");
}
return 0;
}