---
id: 215
lang: en
translation_of: index.md
source_sha256: c9f1ce85f49c0272ed282f6bc78137c69572dc97ad98217e777c29984f7df8e4
title: "CH1401: Rabbit and Rabbit — Solution, and String Hashing"
description: "A quick look at prefix string hashing, then using it to compare two substrings of a DNA sequence in constant time per query."
tags: ["OI","Hashing","Strings","String Hashing"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "字串 in the second section is read as a typo for 子串 (substring) and rendered as “substring”."
  - "进位值 (literally “carry value”) rendered as “radix”."
---

## 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)
$$

<!--more-->

## 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:

```cpp
// 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;
}
```
