手写哈希

对字符串或数组进行hash,p和mod选两个质数冲突比较小。

const ll mod = 1e9 + 7;
const ll p = 1e5 + 7;
ll gethas(int pos, int len)//查找位置pos开始长度为len的串的hash值
{
    
    
    if(pos + len - 1 > n) return -1;
    ll now = has[pos + len - 1] - has[pos - 1];
    now = (now + mod) % mod;
    return now * inv[pos - 1] % mod;
}
//hash过程
        ll np = 1;
        for(int i = 1; i <= n; i++)
        {
    
    
            has[i] = np * p % mod * (ll)(s[i] - 'a') % mod;
            np = np * p % mod;
            has[i] = (has[i] + has[i - 1]) % mod;
        }
        inv[0] = 1;
        for(int i = 1; i <= n; i++)
        {
    
    
            inv[i] = quick_pow(quick_pow(p, i), mod - 2);
        }

猜你喜欢

转载自blog.csdn.net/weixin_43891021/article/details/108976481