Olympiad in Informatics

CH1401: Rabbit and Rabbit — Solution, and String Hashing

String Hashing

Let's first briefly go over string hashing. First, we convert the characters of the string into numbers; for example, we can handle that with the following function:

\[toNum(character) = character - numberOf('a') + 1\]

Then, we define a value \(bitNum\) to serve as the radix. So our prefix hash function has the following recurrence:

\[Hash(i) = Hash(i-1)*bitNum + toNum(S[i])\]

We can explore the subtractive linearity of this prefix hash function. Let \(|S|,|T|\) be the lengths of the two strings. We get:

\[Hash(|T|) = Hash(|S+T|) - Hash(|S|)*bitNum^{|T|}(1.1)\]

Approach to This Problem

For this problem we can directly compute the prefix hashes, then use formula \((1.1)\) to derive the hash values of the substrings, and finally just match them. The code is as follows:

// CH1401.cpp
#include <iostream>
#define ull unsigned long long
using namespace std;
const int maxn = 1000200;
string DNAseq;
ull hs[maxn], bitNum = 133, pows[maxn];

int main()
{
    cin >> DNAseq;
    pows[0] = 1;
    for (int i = 1; i <= DNAseq.length(); i++)
        hs[i] = hs[i - 1] * bitNum + (DNAseq[i - 1] - 'a' + 1), pows[i] = pows[i - 1] * bitNum;
    int T;
    scanf("%d", &T);
    while (T--)
    {
        int l1, l2, r1, r2;
        scanf("%d%d%d%d", &l1, &r1, &l2, &r2);
        ull hash1 = hs[r1] - hs[l1 - 1] * pows[r1 - l1 + 1];
        ull hash2 = hs[r2] - hs[l2 - 1] * pows[r2 - l2 + 1];
        if (hash1 == hash2)
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}