算法竞赛进阶指南---0x14(Hash)兔子与兔子

题面

在这里插入图片描述

题解

  1. 就是字符串hash模板题,将字符串预处理出hash值,然后每次询问判断区间hash值是否相等即可
  2. 字符串hash讲解点这里

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
typedef unsigned long long ULL;
const int N = 1e6 + 10;
const int P = 131;

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() {
    
    

    scanf("%s", str + 1);
    int n = strlen(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 t;
    cin >> t;
    while (t--) {
    
    
        int l1, r1, l2, r2;
        cin >> l1 >> r1 >> l2 >> r2;
        int v1 = get(l1, r1);
        int v2 = get(l2, r2);
        if (v1 == v2) cout << "Yes" << endl;
        else cout << "No" << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/113839107
今日推荐