当比较两个字符串是否相等的时候,最简单的方法是逐个字母去比较,但是有时候这样会太慢,如果我们将每个字符对应于一个26进制的数字,这样的比较的复杂度就是O(1)。但是问题也来了,如果字符串比较长,我们对应的数字也就特别大,比long long 的范围还大怎么办?
解决办法是对哈希值取模,明显这样可能会产生冲突,那么我们就暴力的对应两个哈希值,这样大大的减少了冲突的概率,虽然概率很小,但是如果字符串很多的话,失误的概率还是很大的,措施1,mod取大,措施2,对应两个哈希值
例题:http://codeforces.com/contest/514/problem/C
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull long long
const int maxn=6e5+10;
const ll mod=1e14+7;
ull seed=1331,T[maxn];
char word[maxn];
map<ull,bool>ma;
ull gethash()
{
ull res=0;
int len=strlen(word);
for(int i=0; word[i]; i++)
{
res+=word[len-i-1]*T[i];
res%=mod;
}
return res;
}
bool quer()
{
ull ha=gethash();
int len=strlen(word);
for(int i=0; word[i]; i++)
{
int w=word[i];
for(int j='a'; j<='c'; j++)
{
if(w==j)continue;
ull p=((j-w)*T[len-i-1]%mod+ha+mod)%mod;
if(ma[p])return 1;
}
}
return 0;
}
int main()
{
int n,m;
T[0]=1;
for(int i=1; i<maxn; i++)
{
T[i]=T[i-1]*seed%mod;
}
scanf("%d %d",&n,&m);
for(int i=1; i<=n; i++)
{
scanf("%s",word);
ma[gethash()]=1;
}
for(int i=1; i<=m; i++)
{
scanf("%s",word);
if(quer())
printf("YES\n");
else
printf("NO\n");
}
return 0;
}