多学习。

【哈希表】AcWing841. 字符串哈希

AcWing841. 字符串哈希

题解

前缀字符串哈希
p = 131 或 13331 Q = 2^64 百分之九十九概率不会出现冲突


#include <iostream>

using namespace std;

const int N = 1e5 + 10, P = 131;

typedef unsigned long long ULL;  //用ull存储哈希值溢出即相当于取模

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()
{
    int n, m;
    scanf("%d%d%s",&n, &m, 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;
    int l, r, x, y;
    while(m -- )
    {
        scanf("%d%d%d%d", &l, &r, &x, &y);
        if(get(l, r) == get(x, y)) puts("Yes");
        else puts("No");
    }
    return 0;
}
posted @ 2022-05-21 11:04  czyaaa  阅读(36)  评论(0)    收藏  举报