字符串哈希
字符串哈希
我们定义一个把字符串映射到整数的函数 f,这个 f 称为是 Hash 函数
我们希望这个函数 f 可以方便地帮我们判断两个字符串是否相等
目前普遍使用进制哈希
注意哈希冲突!
将 Hash 函数值一样但原字符串不一样的现象称为哈希冲突
编程时可以采用一种“隐形取余”的简化方法。取空间大小为\(M=2^{64}\),64是unsigned long long 型的长度,一个ull型的哈希值H,当H>M时会自动溢出,等价于自动对M取余,这样能避免低效的取余运算
模板题
//>>>Qiansui
#include<map>
#include<set>
#include<list>
#include<stack>
#include<cmath>
#include<queue>
#include<deque>
#include<cstdio>
#include<string>
#include<vector>
#include<utility>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<functional>
#define ll long long
#define ull unsigned long long
#define mem(x,y) memset(x,y,sizeof(x))
#define debug(x) cout << #x << " = " << x << endl
#define debug2(x,y) cout << #x << " = " << x << " " << #y << " = "<< y << endl
//#define int long long
inline ll read()
{
ll x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-48;ch=getchar();}
return x*f;
}
using namespace std;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<ull,ull> pull;
typedef pair<double,double> pdd;
/*
字符串哈希
这里使用进制哈希
*/
const int maxm=1e4+5,inf=0x3f3f3f3f,mod=998244353;
int n;
ull a[maxm];
set<ull> q;
string ss;
ull stringhash(string s){
ull p=131,ans=0;
for(auto a:s){
ans=ans*p+a;
}
return ans;
}
void solve(){
cin>>n;
for(int i=0;i<n;++i){
cin>>ss;
q.insert(stringhash(ss));
}
cout<<q.size()<<'\n';
return ;
}
signed main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int _=1;
// cin>>_;
while(_--){
solve();
}
return 0;
}
相关资料
相关基础介绍
https://blog.csdn.net/Mikchy/article/details/103995537
求取子串哈希
已知字符串 ss[0 ~ len]的哈希值hash[0 ~ len],则子串[l ~ r]的哈希值为$hash = hash[r] -hash[l-1] * Base ^ {r-l+1} $
记得取余~
string ss;
int len = ss.size(), val;
vector<ll> hash(len + 1, inf);
for(int i = 1; i <= len; ++i){//求子串哈希
hash[i] = (hash[i-1] * base + ss[i] - 'a') % mod;
}
int r = len - 1, l = 0;
ll p = qpow(base, r - l + 1);//视情况而定
val = (mod + hash[r]- hash[l - 1] * p % mod) % mod;
例题
求任意两字符串是否循环同构 hdu 2023 多校1 Cyclically Isomorphic