Some days ago, WJMZBMR learned how to answer the query "how many times does a string x occur in a string s" quickly by preprocessing the string s. But now he wants to make it harder.
So he wants to ask "how many consecutive substrings of s are cyclical isomorphic to a given string x". You are given string s and n strings xi, for each string xi find, how many consecutive substrings of s are cyclical isomorphic to xi.
Two strings are called cyclical isomorphic if one can rotate one string to get the other one. 'Rotate' here means 'to take some consecutive chars (maybe none) from the beginning of a string and put them back at the end of the string in the same order'. For example, string "abcde" can be rotated to string "deabc". We can take characters "abc" from the beginning and put them at the end of "de".
Input
The first line contains a non-empty string s. The length of string s is not greater than 106 characters.
The second line contains an integer n (1 ≤ n ≤ 105) — the number of queries. Then n lines follow: the i-th line contains the string xi — the string for the i-th query. The total length of xi is less than or equal to 106 characters.
In this problem, strings only consist of lowercase English letters.
Output
For each query xi print a single integer that shows how many consecutive substrings of s are cyclical isomorphic to xi. Print the answers to the queries in the order they are given in the input.
Examples
Input
baabaabaaa
5
a
ba
baa
aabaa
aaba
Output
7
5
7
3
5
Input
aabbaa
3
aa
aabb
abba
Output
2
3
3
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To solve this problem, we need to determine how many consecutive substrings of a given string s are cyclical isomorphic to each query string. Cyclical isomorphism means one string can be rotated to form another. The solution involves efficiently determining the minimal rotation for substrings of s and comparing them to the minimal rotations of the query strings.
Approach
Concatenation and Suffix Array:
Concatenate the given string s with itself to handle rotations. This helps in easily determining all possible rotations of substrings.
Construct a suffix array and rank array from the doubled string to efficiently find the minimal rotation for any substring.
Range Minimum Queries (RMQ):
Use a segment tree or a similar structure to quickly find the minimal suffix rank within any range of indices. This helps in determining the starting position of the minimal rotation for any substring.
Rolling Hash:
Precompute rolling hash values for the string s to quickly compute the hash of any substring in constant time. This allows us to efficiently compare substrings using their hash values.
Processing Queries:
For each query, compute its minimal rotation using Booth's algorithm.
Using the preprocessed data, determine the frequency of each minimal rotation's hash among all substrings of s of the query's length.
Solution Code
python
import sys
def main() -> None:
def build_suffix_array(s):
from collections import defaultdict
class SuffixArray:
def __init__(self, s):
self.s = s
self.n = len(self.s)
self.sa = self._build_sa()
self.rank = self._rank()
self.rank_in_sa = self._rank_in_sa()
def _counting_sort(self, size, key):
count = [0] * size
for c in self.s:
count[key(c)] += 1
for i in range(1, size):
count[i] += count[i-1]
res = [0]*self.n
for i in reversed(range(self.n)):
c = key(self.s[i])
count[c] -=1
res[count[c]] = i
return res
def _build_sa(self):
n = self.n
sa = list(range(n))
rank = list(self.s)
tmp = [0]*(n)
max_rank = max(rank) + 2
k = 1
while k <= n:
sa = self._counting_sort(max_rank, lambda x: rank[x])
tmp[sa[0]] = 0
for i in range(1, n):
tmp[sa[i]] = tmp[sa[i-1]]
if rank[sa[i]] != rank[sa[i-1]] or \
(sa[i]+k >=n) != (sa[i-1]+k >=n) or \
(rank[sa[i]+k] if sa[i]+k <n else -1) != rank[sa[i-1]+k] if sa[i-1]+k <n else -1:
tmp[sa[i]] +=1
rank, tmp = tmp, rank
k *=2
if rank[sa[-1]] ==n-1:
break
return sa
def _rank(self):
n = self.n
rank = [0]*n
for i in range(n):
rank[self.sa[i]] = i
return rank
def _rank_in_sa(self):
res = [0]*self.n
for i in range(self.n):
res[self.sa[i]] = i
return res
return SuffixArray(s).sa, SuffixArray(s).rank
class SegmentTree:
def __init__(self, data, default=0, func=lambda a,b:a if (a < b.INFO) else b, INFO=(10**18, -1), node_info=lambda i: (data[i], i)):
n = len(data)
self.n = n
self.size = 1
while self.size < n:
self.size <<=1
self.default = default
self.func = func
self.INFO = INFO
self.tree = [self.getInfo() for _ in range(2*self.size)]
self._initial(node_info)
self._build()
def _initial(self, node_info):
for i in range(self.n):
a = node_info(i)
self.tree[self.size +i] = a
for i in range(self.size-1, 0, -1):
self.tree[i] = self.getInfo()
def getMax(self, a, b):
return self._query(a, b)
def _query(self, l, r):
l += self.size
r += self.size
res_left = self.getInfo()
res_right = self.getInfo()
while l < r:
if l%2 ==1:
res_left = self.func(res_left, self.tree[l])
l +=1
if r%2 ==1:
r -=1
res_right = self.func(self.tree[r], res_right)
l>>=1
r>>=1
return self.func(res_left, res_right)
def getInfo(self):
return self.INFO
def _build(self):
for i in range(self.size-1, 0, -1):
self.tree[i] = self.func(self.tree[2*i], self.tree[2*i+1])
s = sys.stdin.readline().strip()
n = int(sys.stdin.readline())
# Preprocessing
# Step 1: Create doubled_s and build Suffix Array
doubled_s = s + s
sa, rank = build_suffix_array(doubled_s)
n_doubled = len(doubled_s)
# Preprocessing for the rank array
# The rank array `rank` is of doubled_s, and rank[i] is the suffix array's rank for position i.
# We need to build a segment tree over the rank array's values so we can find the minimum in any interval.
data = [ (rank[i], i) for i in range(len(rank))] # (rank_value, original position)
def func(a,b):
if a[0] < b[0]:
return a
else:
return b
seg_tree = SegmentTree(rank, func=func, node_info=lambda i: (rank[i], i))
# Precompute rolling hash for s
MOD = 10**9 + 7
BASE = 911382629
hash_base_pows = [1]*(len(s)+1)
for i in range(1, len(s)+1):
hash_base_pows[i] = (hash_base_pows[i-1] * BASE) % MOD
hash_values = [0]*(len(s)+1)
for i in range(len(s)):
hash_values[i+1] = (hash_values[i] + ord(s[i]) * hash_base_pows[i]) % MOD
def get_hash(l, r):
# from l to r-1 inclusive (0-based)
return (hash_values[r] - hash_values[l]) * pow(hash_base_pows[l], MOD-2, MOD) % MOD
# Booth's algorithm for minimal rotation
def minimal_rotation(s):
n = len(s)
s2 = s*2
sa = build_suffix_array(s2)[0]
suffix_indices = [i for i in range(n + n)]
sorted_suffixes = sorted(suffix_indices, key=lambda x: s2[x:x+n])
min_suffix_ind = sorted_suffixes[0]
min_rotation = s2[min_suffix_ind : min_suffix_ind + n]
return min_rotation
# Alternatively, using Booth's algorithm for minimal rotation:
# Booth's code (if min_rotation implementation is faster)
# keep this for minimal rotation
queries = []
for _ in range(n):
x = sys.stdin.readline().strip()
queries.append( (x, len(x)) )
from collections import defaultdict
m_groups = defaultdict(list)
min_hashes = {}
unique_m = set()
# Compute minimal rotation for each query
for idx in range(n):
x, m_len = queries[idx]
min_rot = minimal_rotation(x)
min_rot_hash = get_hash(0, m_len) # compute the hash of min_rot here using s? Or the x string.
# Wait need to compute minimal rotation for x first, then hash it
# Wait x is the original string, so compute it directly
def compute_x_min_rot_hash(x):
x双重 = x + x
# find minimal rotation:
n_x = len(x)
min_pos = 0
for i in range(1, n_x):
if x双重[i:i+n_x] < x双重[min_pos:min_pos+n_x]:
min_pos = i
min_rot_str = x双重[min_pos:min_pos +n_x]
# compute this string's hash
return get_hash_string(min_rot_str)
# perhaps simple way:
# compute the minimal rotation using Booth's algorithm, then compute its hash by treating it as a string. But how to compute hash of the minimal rotation string?
# Wait the minimal rotation string can be obtained as follows:
min_rot_str = minimal_rotation(x)
min_rot_str_hash = 0
for c in min_rot_str:
min_rot_str_hash = (min_rot_str_hash * BASE + ord(c)) % MOD # just compute directly。
return min_rot_str_hash.
# To compute hash values for min_rot_str:
# Alternatively, compute it as a hash using the same base and mod.
# Rewriting:
min_rot_str = minimal_rotation(x)
min_rot_hash_val = 0
for c in min_rot_str:
min_rot_hash_val = (min_rot_hash_val * BASE + ord(c)) % MOD
min_hashes[idx] = min_rot_hash_val
m_groups[m_len].append( (idx, min_rot_hash_val) )
unique_m.add(m_len)
# Precomputed for all m in unique_m:
results = [0]*(n)
from collections import defaultdict
for m in unique_m:
# Compute frequency of each minimal rotation's hash for substrings of length m in s
freq = defaultdict(int)
n_s = len(s)
for i in range(n_s - m + 1):
# The window starts at i, length m, so the corresponding positions are i to i + m-1 in the original s (part of doubled_s)
start = i
end = i + m -1
L = start
R = end
if L > R:
continue
# query the segment tree to find the minimal_rank position in [L, R]
min_info = seg_tree._query(L, R +1)
min_pos = min_info[1]
# the minimal rotation's string is substr from min_pos to min_pos + m
hash_val = get_hash(min_pos, min_pos + m)
freq[ hash_val ] +=1
# update results
for (idx, target_hash) in m