字符串哈希就是把一个字符串化成一个整数
要得到一个字符串的哈希值首先要将这个字符串的每一个字符的哈希值求出
求单个字符哈希值hash[i]=hash[i-1]*p+idx[s[i]];
p为一个素数为了防止哈希值重复,idx[s[i]]是将字符转化成一个整数
通过单个字符的哈希值求字符串哈希
求字符串的哈希值(给定一个字符串长为N求1<R<L<N)
hash=hash[L]-hash[R-1]*p(L-R+1);
每个字符的哈希值都与前一个相关,而字符串hash求某一段的hash,可以将前面的hash都减去就可以得到单段字符串的哈希
例:求八到十的hash值
hash[8]=hash[7]*p+idx[s[8]]
hash[9]=(hash[7]*p+idx[s[8]])*p+ide[9]
hash[10]=((hash[7]*p+idx[s[8]])*p+ide[9])*p+idx[10]
hash(8~10)=hash[10]-hash[7]*p的三次
#include<iostream>
#include<algorithm>
#include <string.h>
using namespace std;
const int max_n=1000001;
int mod=1e6+10;
char a[max_n];
long long b[max_n],c[max_n];
long long ppow[max_n]={1};
int dex(int c)
{
return c-'a'+1;
}
int main()
{
cin >> a;
int n=strlen(a);
for(int i=1;i<=n;i++)
{
b[i]=(b[i-1]*2333+dex(a[i-1]))%mod+dex(a[i-1])%mod;
ppow[i]=(ppow[i-1]*2333)%mod;
}
int m;
cin >> m;
while(m--)
{
int x,y,x1,y1;
cin >> x>>y>>x1>>y1;
long long ans1,ans2;
ans1=(((b[y]-b[x-1]*ppow[y-x+1])%mod)+mod)%mod;
ans2=(((b[y1]-b[x1-1]*ppow[y1-x1+1])%mod)+mod)%mod;
if(ans1==ans2)
cout << "Yes"<<endl;
else cout<<"No"<<endl;
}
}