哈希常用例题模板&经验杂谈

· · 个人记录

例题

例1.P3370 【模板】字符串哈希

字符串哈希模板,使用双哈希防止被卡,当然这也是个双哈希模板

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int M1=1e9+7;
const int M2=998244353;
const int B1=233;
const int B2=131;
int h1(string s)
{
    int res=0;
    for(int i=0;i<s.size();i++)
    {
        res=(res*B1+s[i])%M1;
    }
    return res;
}
int h2(string s)
{
    int res=0;
    for(int i=0;i<s.size();i++)
    {
        res=(res*B2+s[i])%M2;
    }
    return res;
}
set<pair<int,int> >x;
signed main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        string a;
        cin>>a;
        x.insert(make_pair(h1(a),h2(a)));
    }
    cout<<x.size();
    return 0;
}

哈希函数:

int h1(string s)
{
    int res=0;
    for(int i=0;i<s.size();i++)
    {
        res=(res*B1+s[i])%M1;
    }
    return res;
}

常用大质数M:
998244353
1e9+7
常用小质数B:
233(233333333333...)
131(1313131313131...)
1331(1333..331)
哈希函数:

f(s) = \sum_{i=1}^{l} s[i] \times b^{l-i} \pmod M

例2.P10468 兔子与兔子

多次询问子串哈希的模板

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int B=233;
int h[10000000],b[10000000];
signed main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    string s;
    b[0]=1;
    cin>>s;
    int d=s.size();
    for(int i=1;i<=d;i++)
    {
        h[i]=h[i-1]*B+s[i-1];
        b[i]=b[i-1]*B;
    }
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int l,r,l1,r1;
        cin>>l>>r>>l1>>r1;
        if(h[r]-h[l-1]*b[r-l+1]==h[r1]-h[l1-1]*b[r1-l1+1])
        {
            cout<<"Yes"<<'\n';
        }
        else
        {
            cout<<"No"<<'\n';
        }
    }
    return 0;
}

(吐槽一下"b[10000000]={1}"会在洛谷上报错,莫名其妙的)
言归正传,这是一个多次询问子串哈希的模板,首先推导出f(s_i)即原串长度为i的前缀的哈希值

for(int i=1;i<=s.size();i++)
{
    h[i]=h[i-1]*B+s[i-1];
    b[i]=b[i-1]*B;
}

对于一个f(s_{l~r})的子串的哈希,使用f(s[l..r])=f_r(s)-f_{l-1}(s) \times b^{r-l+1}求出,即

h[r]-h[l-1]*b[r-l+1]

--------------------我是分割线--------------------
最后,我来说两句,如果数据量到了1e6推荐使用双哈希,防止被卡。
参考文献
就这么多,多练也~