#P5829. 【模板】失配树

    ID: 6581 远端评测题 1000ms 512MiB 尝试: 5 已通过: 1 显示难度提高 上传者: 标签>字符串树形数据结构KMP 算法

【模板】失配树

Problem Description

Given a string ss, define its kk-prefix prek\mathit{pre}_k as the substring s1ks_{1\dots k}, and its kk-suffix sufk\mathit{suf}_k as the substring ssk+1ss_{|s|-k+1\dots |s|}, where 1ks1 \le k \le |s|.

Define Border(s)\bold{Border}(s) as the set of strings prei\mathit{pre}_i that satisfy for i[1,s)i \in [1, |s|), prei=sufi\mathit{pre}_i = \mathit{suf}_i. Each element in Border(s)\bold{Border}(s) is called a border\operatorname{border} of the string ss.

There are mm queries. Each query gives p,qp, q. Find the length of the longest common border\operatorname{border} of the p\boldsymbol{p}-prefix and the q\boldsymbol{q}-prefix of ss.

Input Format

The first line contains a string ss.

The second line contains an integer mm.

The next mm lines each contain two integers p,qp, q.

Output Format

For each query, output one integer per line, representing the answer. If there is no common border\operatorname{border}, output 00.

aaaabbabbaa
5
2 4
7 10
3 4
1 2
4 11

1
1
2
0
2

zzaaccaazzccaacczz
3
2 18
10 18
3 5

1
2
0

Hint

Explanation for Sample 2:

For the first query, the 22-prefix and the 1818-prefix are zz and zzaaccaazzccaacczz. Since zz has only one border\operatorname{border}, namely z, the length of the longest common border\operatorname{border} is 11.


For 16%16\% of the testdata, all characters in ss are the same.

For 100%100\% of the testdata, 1p,qs1061\leq p,q \le |s|\leq 10^6, 1m1051 \leq m \leq 10^5, and si[a,z]s_i \in [\texttt{a}, \texttt{z}].

Constraints.

Translated by ChatGPT 5