字符串哈希

字符串哈希 常常可以处理一些用kmp难以处理的题目,是kmp的劲敌。

 

 

 

#include <iostream>

using namespace std;

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

typedef unsigned long long ULL;

ULL h[N],p[N];

char str[N];
int m,n;

ULL check(int l, int r)
{
    return h[r] - h[l - 1]*p[r - l + 1];
} 

int main()
{
    scanf("%d%d%s", &n, &m, str+1);
    p[0] = 1;
    for(int i = 1; i <= n; i ++) 
    {
        p[i] = p[i - 1] * P;
        //这里直接用assii码代表P进制数前面的系数
        h[i] = h[i - 1] * P + str[i];
    }
    while(m--)
    {
        int l1, r1, l2, r2;
        cin>>l1>>r1>>l2>>r2;
        if(check(l1, r1) == check(l2, r2))    puts("Yes");
        else    puts("No");
    }
    return 0;
}

posted @ 2022-06-14 20:11  cxy8  阅读(23)  评论(0)    收藏  举报