牛客竞赛 字符串哈希 白兔的字符串
一道水题,字符串哈希,用链表结构存储,直接上代码了
#pragma GCC optimize("O2")
#define ull unsigned long long
#include <bits/stdc++.h>
using namespace std;
const int maxn=2e6+7,mod=1e5+7;
char str[maxn];
int l,t,L,ans,head[maxn],tot=0;
ull base=123,h[maxn],has[maxn];
struct op{
ull to;
int nxt;
}rode[maxn];
int find(ull x){
int pos=x%mod;
for(int i=head[pos];i!=-1;i=rode[i].nxt)
if(rode[i].to==x)
return 1;
return 0;
}
void add(ull x){
int pos=x%mod;
rode[tot].to=x;
rode[tot].nxt=head[pos];
head[pos]=tot++;//就相当于把每一个取模之后所得的pos位置,都挂上了一个x,消除了哈希冲突
}
void pre(){
for(int i=1;i<=L;i++)
str[i+L]=str[i];
h[0]=1;
for(int i=1;i<maxn;i++)
h[i]=h[i-1]*base;
has[0]=0;
for(int i=1;i<=2*L;i++){
has[i]=has[i-1]*base+str[i];
if(i>=L)
add(has[i]-has[i-L]*h[L]);//获取每一段字符串的哈希值
}
}
int main(){
memset(head,-1,sizeof(head));
scanf("%s",str+1);
L=strlen(str+1);
pre();
scanf("%d",&t);
while(t--){
scanf("%s",str+1);
l=strlen(str+1),ans=0;
for(int i=1;i<=l;i++){
has[i]=has[i-1]*base+str[i];
if(i>=L)
ans+=find(has[i]-has[i-L]*h[L]);//每一段字符串的哈希值
}
printf("%d\n",ans);
}
return 0 ;
}