字符串哈希
title: 字符串哈希
categories:
- ICPC
tags:
- null
abbrlink: ‘51e82117’
date: 2023-09-18 00:00:00
单哈希且用自然溢出代替取模操作,常数小但是容易被卡
单字符串区间内比较,查询子串hash值
typedef unsigned long long ULL;
const int N = 100010, P = 131;
int n, m;
char str[N];
ULL h[N], p[N];
ULL 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, r1, l2, r2;
scanf("%d%d%d%d", &l1, &r1, &l2, &r2);
if (get(l1, r1) == get(l2, r2)) puts("Yes");
else puts("No");
}
return 0;
}
字符串双哈希,多字符串互相比较
const int mod = 998244353;
const ull mod1=212370440130137957ll;
const ull mod2=(1<<30);
const int base=233333;
const double eps = 1e-8;
int n, m;
struct node{ull x,y;
bool operator < (const node& a)const{
return a.x==x?a.y<y:a.x<x;
}
}f[N];
ull hash1(string s){
const int base1=1313131;
ull ans=0,len=s.size();
for(int i=0;i<len;++i)ans=(ans*base1+(ull)s[i])%mod1;
return ans;
}
ull hash2(string s){
ull ans=0,len=s.size();
const int base2=233333;
for(int i=0;i<len;++i)ans=(ans*base2+(ull)s[i])%mod2;
return ans;
}
void solve(){
cin>>n;
for(int i=1;i<=n;i++){
string s;
cin>>s;
f[i].x=hash1(s);
f[i].y=hash2(s);
}
sort(f+1,f+n+1);
int ans=0;
for(int i=1;i<=n;i++){
if(f[i].x==f[i+1].x&&f[i].y==f[i+1].y)continue;
else ans++;
}
cout<<ans<<endl;
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 爱飞鱼的blog!