string_hash(字符串哈希)

本篇介绍一种可以在O(n)的预处理字符串所有的前缀hash值,并在O(1)的时间内查询它的任意字串hash值

其实思想很简单,取一个固定的值 p,把字符串看作p进制数,并分配一个大于0的数值,代表每种字符。一般来讲,我们分配的数值都远小于p。

这里我取的是 p = 131,此时hash值冲突的概率极低。(因为我们认为hash值相等的两段字符串是相同的,所以冲突的概率不能高)。

还有一个问题,溢出了怎么办;

答曰:使用unsigned long long 存数,溢出会自动取模。

#include
// #include
#define oo INT_MAX
#define ll long long
#define maxn  1000099
#define mp(a, b) make_pair(a, b)
#define _rep(i, a, b) for(int i = (a); i <= (b); ++i)
#define _for(i, a, b) for(int i = (a); i < (b) ;++i)
using namespace std;
// using namespace __gnu_pbds;
int n;
char str[maxn];
unsigned ll h[maxn], pre[maxn];
int main(){
    scanf("%s", str + 1);
    int m;cin >> m;
    int p = 131;
    pre[0] = 1;
    int n = strlen(str + 1);
    _rep(i, 1, n){
        h[i] = h[i - 1] * p + (str[i] - 'a' + 1);//以str[i]结尾的hash值
        pre[i] = pre[i - 1] * p;
    }
    _rep(i, 1, m){
        int s1, e1, s2, e2;
       scanf("%d%d%d%d", &s1, &e1, &s2, &e2);
       puts(h[e1] - h[s1 - 1] * pre[e1 - s1 + 1] == h[e2] - h[s2 - 1] * pre[e2 - s2 + 1]? "Yes" : "No");
    }
    system("pause");
}

你可能感兴趣的:(数据结构)