We need to answer multiple queries: For each query string x_i, count the number of substrings of s (consecutive) that are cyclical isomorphic to x_i.
Constraints: |s| <= 1e6, total length of all xi <= 1e6, n up to 1e5. So we need efficient per query.
Observation: Two strings are cyclical isomorphic if one is a rotation of the other. That is, there exists a shift k such that x[i] = y[(i+k) mod len] for all i. So essentially, they are equal if we consider strings as cyclic. Counting substrings of s that are rotations of x_i. Equivalent to: For each length L = |x_i|, we need to count substrings of s of length L that are rotations of x_i. Since rotation equivalence can be captured by minimal representation: The lexicographically smallest rotation (or using Booth's algorithm) is a canonical form for cyclic equivalence (for strings over alphabet). So we can compute the minimal rotation (also known as the least circular shift) of each x_i, and also for each substring of s of length L we need to know whether its minimal rotation equals that canonical form. But L varies per query.
We need to answer many queries for different lengths and canonical forms. Could we preprocess s such that for each length L (up to maybe 1e6) we have a data structure to query frequency of minimal rotation of substrings of length L? Since total length of queries is 1e6, we could potentially compute the minimal rotation for each substring of s? That would be O(|s|^2) impossible.
We need a smarter approach. The problem resembles: Given a text s, multiple pattern queries where patterns are considered under rotation equivalence. So we want to count occurrences of any rotation of x_i as a substring in s. That's similar to pattern matching with pattern being a set of all rotations. Since total length of all rotations is L_i * L_i (but we can combine using something like: we can check if any rotation of x_i appears as a substring of s). But we need count of substrings of s (i.e., positions in s) that are rotations of x_i. Equivalent to count positions i (0-indexed) such that s[i:i+L] is a rotation of x.
One idea: For each query x, build a string that encodes all rotations, maybe using doubled string: x+x, then any rotation appears as a substring of length L in x+x. Then a substring of s is a rotation of x iff it appears as a substring of x+x, but careful: It must be exactly length L, and any substring of length L of x+x (except those crossing the boundary? Actually all rotations are exactly length L substrings of x+x, from position 0 to L-1 inclusive; there are L rotations). So the condition: substring t (len L) is a rotation of x iff t is a substring of x+x (of length L) and t is not necessarily distinct; but we need to check equality. But that doesn't directly help for counting in s.
We could treat each query separately by doing string matching with Aho-Corasick or suffix automaton that can match any rotation? Maybe we can convert each query x to its minimal rotation, and then we want to count substrings of s of length L whose minimal rotation equals that canonical form. So we need to compute minimal rotation for every substring of s? That is too many.
Alternative: Using polynomial hashing with rolling hash and handling rotations. If we consider the double string approach: t is a rotation of x iff there exists a split such that t = x[k..L-1] + x[0..k-1]. This is equivalent to t being a substring of length L of the doubled string x+x. So for a given query, we could build a hash of all rotations of x (maybe store in a hash set) and then slide over s to count substrings of length L whose hash is in that set. Since total length of all queries is 1e6, but each query length L_i, the number of rotations is L_i, so total rotations sum over L_i can be up to sum L_i^2? Wait careful: For each query, L_i, number of rotations is L_i. If we store all rotations, total across queries sum L_i, which is <= 1e6? Actually total length of all x_i <= 1e6, but L_i is length of each x_i. sum L_i <= 1e6. However, sum over L_i (number of rotations) equals sum L_i <= 1e6, because each rotation is a string of length L_i; but storing all rotations as separate strings would cost total length sum_{i} L_i * L_i? No: If you store each rotation as a string of length L_i, then total characters across all rotations would be sum_i L_i * L_i, which could be up to (1e6)^2 if one query is long. But we don't need to store the strings explicitly; we can store hashes of each rotation. A hash value takes O(1) space, so storing L_i hashes for each query is okay: total number of hash values stored = sum_i L_i <= 1e6. That's acceptable! However, we need to compute these hashes efficiently for each query.
But then for each query, we need to scan s and for each substring of length L_i compute its hash and check if it belongs to the set of rotation hashes for that query. That would be O(|s|) per query, leading to O(n * |s|) which is too big (n up to 1e5, s up to 1e6). Not feasible.
We need to answer many queries faster. Since total sum of lengths of queries is 1e6, maybe we can group queries by length? For each length L, we have many queries (different x). For each length L, we could process all substrings of s of length L in one pass: compute hash of each substring, and then for each query of that length, check if that hash is in the set of rotation hashes for that query, accumulate count. However, for a given length L, there may be many queries; but total queries across all lengths is n. The number of distinct lengths is at most sqrt(total length?) Actually total sum of lengths <= 1e6, so number of distinct lengths can be up to 1e6 in worst-case (e.g., each query length 1, many queries). But we can handle lengths separately: For each distinct length L, we iterate over all substrings of s of that length (which are |s|-L+1 substrings, up to 1e6). If there are many different L, doing this per L would be O(number_of_distinct_lengths * |s|) which could be large (if many distinct lengths, like 1e5 lengths, but total sum of lengths is 1e6, but number of distinct lengths could be up to 1e5 if lengths are unique. That could be 1e5 * 1e6 = 1e11). So we need a better way.
Maybe we can precompute for each position in s something like a hash of the substring, and then for each query we can retrieve counts via map of hashes? But we need to count substrings of length L that are rotations of x. That is, we need to consider all substrings of length L and compute a canonical representation (like minimal rotation) and then count frequencies per canonical representation per length. Then each query just looks up frequency of its canonical representation for length L. That would be ideal: Preprocess all substrings of s? But there are O(|s|^2) substrings.
However, note that we only care about substrings of lengths that appear in queries. Since total sum of lengths of queries is 1e6, the number of distinct lengths L that appear among queries is bounded by the total number of queries, but could be up to 1e5. But we can perhaps process all substrings of s for all lengths needed in one go using something like a suffix automaton or suffix array? Counting occurrences of patterns via automaton can handle multiple patterns of varying lengths efficiently if we build a data structure on s (like suffix automaton or suffix tree) that can answer for each pattern how many times it occurs as a substring. But here pattern is not fixed; we need to count substrings that are rotations of x. That's like counting occurrences of any rotation. So for each query, we want number of substrings of s that equal any rotation of x. But note that each rotation of x is a string of length L. So essentially we want sum over rotations r of count of occurrences of r as a substring in s. However, rotations are distinct strings (could have repeats if x is periodic). So we could compute for each rotation its occurrence count using a suffix automaton (which can count occurrences of a pattern in O(L) after preprocessing s). Then for each query we sum over its rotations. Since total length of all rotations across all queries is sum_i L_i <= 1e6, we could process each rotation individually: For each query, we compute all rotations (or distinct rotations) of x, for each rotation pattern, we query the suffix automaton for number of occurrences, sum them, but careful: Overlap? Substrings of s are positions; if a substring matches multiple rotations? Actually a given substring t of length L corresponds to exactly one rotation equivalence class; it can't be equal to two different rotations of x unless those rotations are equal (i.e., if x has period d, then some rotations coincide). So we need to count each substring exactly once. If we sum occurrence counts of each distinct rotation, we would count each occurrence multiple times if the rotations are distinct but the same substring matches only one rotation. But each occurrence (position) will be counted exactly once if we consider the specific rotation it matches: that rotation is unique (since if t equals two different rotations of x, then those rotations are equal as strings, so they are same rotation). So summing counts of all distinct rotation strings gives the number of positions where the substring equals some rotation; but if rotations are distinct as strings, then each occurrence will be counted exactly once because it matches exactly one of those strings (the one equal to t). But is there any possibility that the same position could match two different rotations? That would require that the substring equals two different strings, which is impossible unless those strings are identical. So summing counts of distinct rotations gives the desired count. However, need to be careful: In suffix automaton, each occurrence count for a pattern counts the number of times that exact string occurs as a substring. Different rotation strings are different unless x has periodicity. So if we sum them, we might double count if some rotation strings are the same? But if they are identical, we need to consider distinct rotations only. So we should take the set of distinct rotation strings. That's fine.
Thus a straightforward approach: Preprocess s into a suffix automaton (or suffix array with LCP) that can answer for any pattern its number of occurrences in O(|pattern|) after O(|s|) preprocessing. Then for each query x, generate all distinct rotations of x (maybe use minimal rotation to deduplicate, but better generate all L rotations, compute their hash, store unique ones, and for each distinct rotation pattern, query the automaton to get its occurrence count, sum them. Complexity: For each query, we need to generate rotations and query each. The total number of rotations across all queries is sum L_i <= 1e6. Querying each rotation pattern in suffix automaton costs O(|pattern|) = O(L_i) per pattern. That would be O(total characters across all rotations) = sum_i (L_i * number_of_distinct_rotations_i). In worst case, if each query has L_i distinct rotations (i.e., x_i is primitive), then number_of_distinct_rotations_i = L_i, and each pattern length = L_i, so cost per query O(L_i^2) because for each rotation we need to traverse L_i characters. That's too much: total could be sum L_i^2, which could be up to (1e6)^2? But note sum L_i <= 1e6, but L_i^2 summed can be large. For example, one query of length 1e6: then L_i^2 = 1e12. So not feasible.
We need to answer each query more efficiently. For a given x (length L), we need to count the number of substrings of s that are equal to some rotation of x. That's like counting all substrings of s of length L that belong to the set R(x) of rotations. Could we use a rolling hash on s to compute a frequency map for all substrings of length L? For each length L, we could compute hashes of all substrings of s of length L (O(|s|) time), and then for each query of that length, we can compute the set of rotation hashes and sum the frequencies from the map. That would be O(|s|) per distinct length, plus O(total rotation hashes) to look up frequencies. Since total rotation hashes sum L_i <= 1e6, that's fine. But the issue is number of distinct lengths. If there are many distinct lengths, we would have to iterate over s for each length separately, which could be costly.
However, note that sum of lengths of queries is 1e6, but the number of distinct lengths can be at most 1e6 theoretically (if each query length is unique and each length is up to 1e6). But in practice, n max 1e5, so distinct lengths <= 1e5. Still, if we do O(|s|) per distinct length, that's up to 1e5 * 1e6 = 1e11, too high.
But we can perhaps process all lengths together using a suffix automaton? Or we can use an approach based on building a hash for each substring of s but we can compute for all lengths simultaneously? That seems like building a suffix tree and enumerating all substrings, which is O(|s|^2) in number of substrings.
Alternatively, maybe we can use a different canonical representation: For a string, its minimal rotation can be computed in O(L) time using Booth's algorithm. If we could compute for every substring of s its minimal rotation efficiently, we could bucket by length and minimal rotation. But there are O(|s|^2) substrings.
Observation: The total length of s is up to 1e6, so we might consider building a suffix automaton and then for each query x, we can find all occurrences of its minimal rotation? But that only counts substrings equal to the minimal rotation, not all rotations. However, note that if a substring is a rotation of x, its minimal rotation equals the minimal rotation of x (since minimal rotation is invariant under rotation). So the condition "substring t is rotation of x" is equivalent to "minimal_rotation(t) = minimal_rotation(x)". So if we could compute minimal rotation for all substrings of s and aggregate by length and minimal rotation, we would answer quickly. But again, many substrings.
Wait: Could we compute for each position i and length L the minimal rotation of s[i:i+L] efficiently using some precomputation? Possibly using lexicographically minimal suffix array with doubling? Or we can use Lyndon factorization? There might be known techniques: Given a string s, preprocess to answer queries: for a substring s[l..r], find its minimal rotation. This can be answered in O(1) or O(log n) after some preprocessing (like using suffix array + RMQ for comparing rotations). Actually, the minimal rotation of a string t can be found by considering the string t+t and finding its lexicographically smallest suffix of length at least |t|. So the minimal rotation corresponds to the smallest suffix of t+t that starts at position < |t|. For a substring of s, we can form its doubled version in O(1) using the original string? Not directly.
But we don't need to answer arbitrary substring minimal rotation queries; we need to count how many substrings of a fixed length L have a given minimal rotation (canonical form). Since L is fixed per query, we could for each L compute minimal rotations for all substrings of length L. That would be O(|s| * cost per substring). If we can compute minimal rotation in O(1) after some preprocessing, then for each L we can process all substrings in O(|s|) time. Then total across distinct L would be O(D * |s|) where D is number of distinct lengths, which is too many.
But maybe we can group lengths by small vs large. A classic trick: For pattern matching with many queries, we can handle short patterns with one method (like hashing all substrings of s of length up to some threshold B), and long patterns with another method (like individual matching using KMP or Aho-Corasick). Because total sum of pattern lengths is bounded, number of long patterns is limited (since each long pattern has length > B, so there are at most total length / B such patterns). This is a common technique: Use a threshold to separate "short" and "long" queries.
So we can do:
-
Let B be a threshold (e.g., sqrt(|s|) or maybe 1000? Given constraints, we can decide.
-
For lengths L <= B: We will precompute for each possible L (up to B) a frequency map of all substrings of s of length L (maybe by hashing). Since B could be up to sqrt(1e6) ~ 1000, number of lengths L <= B is at most B = 1000. For each L from 1 to B, we can slide over s, compute hash of each substring of length L, and store in a map (or we could store counts per hash). That would cost O(B * |s|) time which is about 1000*1e6 = 1e9, borderline but maybe okay with optimization? 1e9 operations might be too heavy in Python (we need to implement in Python? The problem likely expects C++ but we can think algorithmically. However, we need to provide solution explanation, not necessarily code. But we need to design an efficient algorithm. In C++ 1e9 operations might be borderline but can be optimized if we use rolling hash and O(1) updates per step. 1e9 might be okay with careful coding? But given constraints (1e6 length, B=1000 gives 1e9 operations, which is heavy but perhaps doable with low-level C++? I'd prefer a better method.
Alternatively, we could not precompute all L up to B, but only those L that actually appear among queries. Since total sum of lengths is 1e6, the number of distinct lengths that are <= B is at most B, but they could all appear. However, precomputing for each such L would be O(|s| * distinct_small_lengths). If many small lengths appear (like many queries of length 1,2,3,... up to 1000) then it's up to 1000*1e6 = 1e9. Possibly acceptable if we use fast hash and arrays? But still heavy. Could use B = 500 to reduce to 5e8. Or we could use a different method for small lengths: For each position i, we could compute minimal rotation for all substrings starting at i up to length B? Not.
Maybe we can use suffix automaton to answer per query directly in O(|x|) regardless of length, by cleverly handling rotations. How to answer "count substrings that are rotations of x" using automaton? Could we build an automaton for s and then for x we can compute something like: All rotations of x correspond to all cyclic shifts. If we consider the string x+x, and we want to find all substrings of s that appear as a substring of x+x (of length L). That's essentially: For each rotation, we want to know if it appears in s. But we need to count occurrences, not just existence. However, we could compute for each rotation its number of occurrences as a substring via automaton in O(L) each. That gave O(L^2) per query.
But maybe we can use the concept of "cyclic pattern matching" via automaton: Build an automaton for s (like suffix automaton) that can count occurrences of any given pattern. For x, we could compute something like: For each rotation, they share the same set of characters and many suffixes/prefixes. Perhaps we can compute the sum of occurrences of all rotations in O(L) by using some combinatorial property? For example, we could consider the string x and we want to count occurrences of all its rotations in s. That is similar to counting occurrences of all conjugates. Could be done by building a string x+x and then running a KMP search for x in s? Not exactly.
Another idea: Use polynomial hashing and store all substring hashes of s in a global hash table for all lengths? That would be O(|s|^2) memory.
Maybe we can use a suffix array + LCP and then for each query length L, we can count the number of occurrences of any rotation. Could be done by considering the concatenation x+x and building its suffix array? Not.
Given the constraints, the typical solution for such problem (as known from Codeforces problem "Cyclical Quest" maybe?) is to use suffix automaton and handle rotations by adding a virtual edge for each character? Actually there is Codeforces problem 235C "Cyclical Quest" which is exactly this! I recall a problem: "Cyclical Quest" (CF 235C) where you have a text s and n queries, each query a pattern x, and you need to count the number of substrings of s that are cyclic shifts of x. That's exactly the same statement! And the solution uses a suffix automaton with precomputed counts and then for each query, you traverse the automaton with x concatenated with itself (x+x), but you must avoid counting matches that are longer than L. The known solution: Build a suffix automaton for s. Preprocess each state with "occurrence count" (number of end positions). For each query string x of length L, we consider the string t = x + x (to simulate all rotations). Then we walk through the automaton with t, but we maintain the current length matched (len). While traversing, we ensure that the matched substring length does not exceed L. Whenever we reach a state after processing a character, if the current length is >= L, we need to consider that we have matched a substring of length exactly L which is a rotation. But careful: In the automaton, a state corresponds to a set of end positions and can represent substrings of various lengths up to maxlen of that state. To count each occurrence exactly once, we need to add the occurrence count of the state corresponding to the longest suffix that is of length at least L and that we have not already counted for that rotation? Actually the standard solution for "Cyclical Quest" is as follows (I recall from editorial):
-
Build a suffix automaton of s.
-
For each state, compute cnt (the number of occurrences of substrings represented by that state) via topological order on len.
-
For each query pattern x of length L:
- Let t = x + x (length 2L).
- Traverse the automaton with t, maintaining current state v and current length l (the length of the current matched substring).
- For each position i from 0 to 2L-1 (or 1-indexed), we consume t[i], updating v and l using standard automaton transitions, handling cases where transition missing, moving via suffix links until we find a state with transition.
- While we traverse, if at some step after updating we have l > L, we need to shrink l by moving along suffix links until we have l <= L and also the current state's maxlen >= something? Actually the typical method: We need to count for each rotation (each position i where i >= L-1, i.e., the end of a length-L window in t) the number of occurrences of the substring of length L ending at that position (which is a rotation of x). To count these occurrences in the automaton, we keep track of the state representing the current matched substring (the longest suffix of the processed prefix that occurs in s). After processing each character, we have a state v and length l (the length of the matched substring). If l >= L, we need to find the state that corresponds to a substring of length exactly L? Actually any substring of length L that ends at current position and matches the suffix of processed prefix. In the automaton, substrings of length exactly L that end at this position correspond to some state that has maxlen >= L and minlen (which is link's maxlen+1) <= L, and we need to get the state that represents that substring (or at least its occurrence count). Since we have v representing the longest matched suffix, we can walk from v via suffix links until we find a state u whose maxlen >= L and (link of u).maxlen < L (i.e., u's minlen <= L <= u's maxlen). Then u is the state that represents all substrings of length between minlen and maxlen, including length L. However, if we do this for each position i where i >= L-1, we could add cnt[u] to answer, but careful: same occurrence might be counted multiple times for different rotations? Actually we want to count each occurrence of each rotation as a substring of s. In the traversal of t = x+x, as we slide through, each time we have a window of length L that corresponds to a rotation, we want to count how many times that particular string (the rotation) appears in s. That's exactly the number of occurrences of that string. The automaton can give that count for the state representing that string (if the string is exactly a substring). However, the automaton does not have a state for each distinct substring; but if the string exists, there is a state that corresponds to its end position class, and the cnt of that state gives the number of occurrences of that string. We can locate that state by traversing the automaton with the string itself. In our traversal of t, when we are at position i (i from L-1 to 2L-1), the substring t[i-L+1..i] is a rotation. At that point, we have processed prefix up to i, and our current state v and length l represent some suffix of that prefix of length up to l. To get the state corresponding exactly to the substring t[i-L+1..i] (length L), we need to ensure we are in a state that contains that substring. Typically, we can get it by: if l >= L, we can move from v up via suffix links until we find a state u whose maxlen >= L and (link(u)).maxlen < L (i.e., minlen <= L <= maxlen). Then that state u is the state that represents that substring (since any substring of length L that ends at this position is represented by some state; if we are at the end of the substring, the state we get by following suffix links to the right length should be the one representing the substring). However, we need to be careful that we don't count the same state multiple times for the same query? Actually, for each rotation we want to add cnt[u] once. But note that as we slide, the substring changes. However, it's possible that two different rotations (different strings) map to the same automaton state? Possibly if they are the same string (i.e., if the pattern has periodicity, some rotations coincide). But we need to count each distinct rotation string only once? Wait, we are counting occurrences of substrings of s that are cyclical isomorphic to x. That means for each position in s where the substring equals some rotation, we count it. If two different rotations are the same string (because x is periodic), then that same string is still a rotation, but we shouldn't double count the same occurrence for two different rotations because it's the same substring. But in our method, we are iterating over each rotation window in t and adding cnt[u] for that specific string. If the same string appears as multiple windows in t (i.e., if x has period d, then some rotations are identical), then we would add the same cnt multiple times, overcounting. So we must deduplicate: for each distinct rotation string, we should add its occurrence count exactly once. So we need to collect distinct states or distinct strings that we encounter when i runs from L-1 to 2L-1, and sum cnt for distinct ones. In the known solution for CF 235C, they handle this by marking states to avoid double counting within a query. The editorial says: For each query, we traverse t = x+x, and when we have l > L we reduce l to L. When we have l == L, we can consider the current state, but we must ensure we haven't counted this state before in this query. So we maintain a "last visited" timestamp per state to check if it has been added in this query. Actually, I recall a solution:
That's the gist. Also, to avoid O(L^2) we adjust state in O(1) amortized using while loops, but overall traversal is O(|t|) = O(L). Since we process each query in O(L) time, total O(total length of queries) = O(1e6), which is perfect!
So the known solution from CF 235C is indeed using suffix automaton. Let's recall details precisely.
I'll reconstruct the algorithm.
First, build suffix automaton for string s.
In SAM, each state has:
- len: the length of the longest string in that state.
- link: suffix link.
- next[26]: transitions.
- cnt: number of occurrences (endpos size) for that state. Usually we compute by initially setting cnt=1 for each state corresponding to a prefix (the states visited when adding each character), then after building, we sort states by len descending and propagate cnt to link.
Now for each query x of length L:
We consider string t = x + x (to cover all rotations). We will traverse t with the automaton, but we only care about substrings of length exactly L.
We maintain:
- v: current state (initially root).
- l: current length of the matched substring (the longest suffix of processed prefix that is in the automaton).
- ans: total count for this query.
We also have a global array "vis" (or maybe map) to mark states that have been added to ans in this query, to avoid double counting. Also we may need an array "last" to store the timestamp (query id) to avoid resetting marks each query.
We iterate over each character c in t (for i from 0 to 2L-1):
- While v != root and next[v][c] is undefined: v = link[v], l = len[v] (or we need to update l accordingly? Actually after following suffix links, the matched length becomes len[v] because v represents some suffix of the processed prefix. When we fail to transition, we move to link, and the matched length should be updated to len[v] (since we are now at a state whose longest string is a suffix). But careful: When we move to link[v], the matched length should be set to len[link[v]]? Usually in SAM traversal, we keep l as the length of the current match. If we fail to transition from state v with character c, we go to link[v] and try again, and set l = len[link[v]] (since the new state's longest string length is len[link[v]]). Actually the typical algorithm for finding occurrences of a pattern: start at root, l=0. For each character c:
while v has no edge c and v != root: v = link[v];
if v has edge c: v = go(v,c); l++;
else: v = root; l=0.
But that's for a standard automaton where we want to find longest substring. However, this simple method does not maintain l correctly when we follow suffix links due to missing edges? Actually the standard method for SAM when used as a DFA for matching (like Aho-Corasick style) is: we keep state v and length l. When we encounter c:
if there is transition from v with c:
v = next[v][c]; l++;
else:
while v != root and next[v][c] is None: v = link[v];
if next[v][c] is not None:
l = len[v] + 1; //? This is tricky.
else:
v = root; l=0.
But we need to maintain l as the length of the current matched substring. The known approach for this problem (CF 235C) uses a slightly different method: They keep track of v and l, and when they need to shrink to length L, they adjust via suffix links.
Let me search memory: There is a known code snippet for problem 235C:
int n = strlen(s);
for(int i=0;i<n;i++) add(s[i]-'a');
for(int i=1;i<=sz;i++) c[l[i]]++;
for(int i=1;i<=sz;i++) c[i]+=c[i-1];
for(int i=1;i<=sz;i++) order[c[l[i]]--]=i;
for(int i=sz;i>=1;i--) {
int v = order[i];
cnt[link[v]] += cnt[v];
}
// then for each query:
scanf("%s",p);
int m = strlen(p);
for(int i=0;i<m;i++) p[i+m]=p[i];
int v=1, len=0;
long long ans=0;
for(int i=0;i<2*m-1;i++) {
int c = p[i]-'a';
while(v!=1 && !next[v][c]) v=link[v], len=l[v];
if(next[v][c]) v=next[v][c], len++;
else v=1, len=0;
if(len>m) {
while(l[link[v]]>=m) v=link[v];
len=m;
}
if(len>=m && vis[v]!=cur) {
vis[v]=cur;
ans+=cnt[v];
}
}
Something like that. Also they ensure that they only consider the first 2m-1 characters? Actually they use 2*m-1 to avoid double counting the full rotation twice? Let's analyze.
We need to consider all rotations of x, which are exactly the substrings of length m in the string t = x+x, but there are m rotations. However, if we take t of length 2m, the substrings of length m starting at positions 0..m-1 are the rotations. Starting at position m gives the original x again (same as start 0). So we need positions from 0 to m-1 inclusive. But if we process t of length 2m, the windows starting at 0..m are m+1? Actually windows of length m over t of length 2m: positions start=0 to start=m inclusive? Let's compute: If t length = 2m, then number of substrings of length m is 2m - m + 1 = m+1. Those are indices 0..m. The substring at start m is x (since t[m..2m-1] = x). So we have rotations for start 0..m-1 (m substrings) plus start m which is same as start 0? Actually start 0 gives x, start m also gives x, so we get duplicate of the original string. So we should process only first 2m-1 characters? Let's test: t = x+x, length 2m. Substrings of length m starting at positions 0..m inclusive. That gives m+1 substrings. But rotations are exactly m distinct strings (if x not all same? some may duplicate). But the set of rotations is exactly the substrings starting at positions 0..m-1. Starting at m gives x again which is same as starting at 0. So to avoid double counting the same rotation (especially if x is periodic, we might still double count?), we need to process only start positions 0..m-1. In the traversal, as we read characters, after reading i-th character (0-indexed), we have processed prefix ending at i. The substring of length m ending at i corresponds to start i-m+1, which is valid if i-m+1 >= 0 and i-m+1 <= m-1 => i ∈ [m-1, 2m-2]. So if we process exactly 2m-1 characters (i from 0 to 2m-2), the ending positions i = m-1,...,2m-2 correspond to starts 0,...,m-1. So processing t of length 2m-1 is enough to cover all rotations exactly once. If we process 2m characters, then at i=2m-1, start = m, which is the extra duplicate. So we should only process first 2m-1 characters.
Thus the loop goes for i=0 to 2*m-2 (inclusive). That's 2m-1 iterations.
Now the algorithm:
Initialize curState = root, curLen = 0.
For each character c in t (for i in range(2*m-1)):
While curState != root and transition(curState, c) is None:
curState = link[curState]
curLen = len[curState] // because the longest string represented by curState is len[curState]
If transition exists:
curState = transition(curState, c)
curLen += 1
Else:
curState = root
curLen = 0
// Now we have matched a suffix of processed prefix with length curLen.
// If curLen > m, we need to adjust so that the matched substring length is at most m.
if curLen > m:
while len[link[curState]] >= m: // Actually we want to find state where its maxlen (len) is still >= m but its link's maxlen < m, so that the state contains substrings of length m.
curState = link[curState]
curLen = m // Since we know there is a substring of length m, we set curLen=m.
// Now if curLen >= m, we have found the state that represents the current substring of length m (the one ending at i). But we must ensure that we haven't added this state before in this query.
if curLen >= m:
// curState might represent substrings longer than m; we need to get the state that exactly contains the substring of length m? Actually if we adjusted as above, curState should satisfy len[link[curState]] < m <= len[curState]. So curState's interval includes length m. So any substring of length m that ends at current position is represented by this state (or a state reachable by suffix links? Actually all substrings of a given length that end at a given position correspond to the state on the path from the state representing the entire processed prefix (the state we are in after reading the character) up to root; the unique state where len[link] < length <= len is the one that contains that length. So after adjustment, curState is precisely that state. So we can use its cnt.
if lastVisited[curState] != queryID:
lastVisited[curState] = queryID
ans += cnt[curState]
Note: The adjustment condition: while len[link[curState]] >= m: curState = link[curState]. This ensures that after the loop, len[link[curState]] < m <= len[curState]. Because initially curLen > m, so len[curState] >= curLen > m. The link state has len less than len[curState]. If len[link[curState]] is still >= m, then the substring of length m is also represented by link[curState] (since link's maxlen is >= m), so we go up. So we find the highest state (closest to root) that still has maxlen >= m, which ensures its link has maxlen < m. That state's interval includes length m. So it's correct.
But we also need to handle the case when curLen == m but we haven't adjusted; then we should also ensure that curState is the correct state representing length m. If curLen == m, we might be in a state where len[curState] >= m, but maybe len[link[curState]] >= m? That would mean that the substring of length m is also represented by a longer state? Actually if len[link] >= m, then the substring of length m is actually represented by link state, because link state contains longer strings? Wait: The state's interval is (len[link], len]. So if len[link] >= m, then m is not in (len[link], len] because that interval starts above len[link]. So if len[link] >= m, then m is <= len[link], meaning that the substring of length m is not represented by curState, but by some ancestor. So we must adjust similarly: while len[link[curState]] >= m: curState = link[curState]. This ensures that after loop, len[link] < m <= len. So we should always perform this adjustment when curLen >= m, not only when curLen > m. So the condition should be: if curLen >= m: then while len[link[curState]] >= m: curState = link[curState]; (and possibly set curLen = m if it was larger). Actually if curLen >= m, after adjustment, we may have curState such that len[curState] >= m and len[link] < m. That's the correct state. Then we can add cnt if not visited.
But we also need to ensure that after adjustment, the matched length is at least m, but we may have reduced curLen? In the case curLen > m, we set curLen = m after adjustment. In case curLen == m, we might not change curLen. But careful: After adjusting state upward, the new state's len might be less than original curLen, but we know that the substring of length m exists and its state is after adjustment; the current matched length after reading characters is still curLen originally. But we are only using curLen to know that we have a match of at least m; after adjusting state, we don't need curLen for anything else. So we can keep curLen as is, but we should set curLen = m if we changed state? Actually the condition for adding is curLen >= m, and after adjusting state we have a state that includes length m. So we can simply do:
if curLen >= m:
while len[link[curState]] >= m:
curState = link[curState];
if curLen > m: curLen = m; // optional, not needed for addition but for later steps maybe needed because we may exceed m again later.
if lastSeen[curState] != queryID:
lastSeen[curState] = queryID
ans += cnt[curState]
But we also need to maintain curLen correctly for subsequent steps: In later iterations, when we continue processing characters, we need to have the correct matched length. If we artificially set curLen = m after adjustment, that's okay because the actual matched suffix length is at least m, but we are capping it to m for the purpose of ensuring that we can shrink later when we exceed again. However, the algorithm described in many solutions sets curLen = m after the while loop if curLen > m, and does not set if curLen == m. That seems to be common.
Also, the initial while loop for missing transition: when we follow suffix links, we need to update curLen to len[curState]? In the standard algorithm for SAM matching, when we fail to transition and go to link, we set curLen = len[curState] (the max length of that state). Because after moving to link, the new matched length should be the length of the longest string represented by that state (since we are taking a suffix of the previously matched string). This is crucial. So:
while curState != root and not transition(curState, c):
curState = link[curState]
curLen = len[curState]
Then if transition exists:
curState = transition(curState, c)
curLen += 1
else:
curState = root
curLen = 0
This is typical.
Now, after processing each character, we have a state and length representing the longest suffix of processed prefix that is in the automaton. Then we need to get the state that contains the substring of length m that ends at this position. That's done as above.
Now about marking visited states: Since a rotation might lead to the same state multiple times (if x has periodicity), we only add cnt once per query per state. But note: Could two distinct rotations map to the same state? Yes, if they are the same string, they map to same state. If they are different strings but happen to have the same endpos equivalence? In SAM, each distinct substring corresponds to a unique state? Actually each substring is represented by exactly one state: the state that corresponds to the equivalence class of end positions. For a given string, there is a unique state that contains it (the state whose len interval covers its length and such that traversing the automaton with the string leads to that state). So two different strings (rotations) that are distinct would lead to different states (if they are distinct substrings). But could they lead to the same state? Possibly if the strings are different but belong to the same endpos class? That cannot happen because each state corresponds to a set of substrings that all share the same endpos set. If two distinct substrings have the same set of end positions, they are in the same state. For example, in string "ababa", substrings "ab" and "b" might have different endpos? Actually in SAM, each state corresponds to a set of substrings that are suffixes of each other, all of which end at the same positions. So distinct strings in the same state have different lengths. So if two rotations have same length L, they cannot be in the same state unless they are identical strings, because a state can contain at most one substring of a given length? Actually a state contains substrings of lengths from minlen to maxlen inclusive. If two strings of the same length L are both in the state, then they would both be substrings with the same set of end positions and same length. Could they be different? Possibly if they are different but have the same set of occurrences? In a deterministic automaton, if you traverse with a string, you end at a state that represents that string. Two different strings would lead to different states (since transitions are deterministic). However, could two different strings lead to the same state? Only if the automaton is not minimal? In SAM, it's deterministic and each string leads to a unique state (though multiple strings may lead to same state if they are different but after reading them you end at same state? That would mean that after reading those strings, the automaton ends in same state, implying that the set of possible continuations is same; but the strings themselves are different. For example, in a suffix automaton, reading a string leads to a state that represents the set of end positions of that string. Two distinct strings may have the same set of end positions, e.g., in string "aaa", substrings "a", "aa", "aaa" have different endpos sets? Actually for "aaa", the SAM states: after reading "a", you are in a state representing end positions {1,2,3}. After reading "aa", you go to a different state? Let's recall SAM construction: For each distinct substring, there is a path, but different substrings can lead to the same state only if they are suffixes of each other? Actually in SAM, each state corresponds to a set of substrings that are all suffixes of each other, and they share the same endpos set. Different substrings in the same state have different lengths, and they are nested: the longer one is a suffix of the shorter one? Wait, each state has a set of strings which are all the suffixes of the longest string in that state that are longer than the longest string of the link state. So they form a contiguous range of lengths. So if two strings have the same length, they cannot be in the same state (unless they are the same string). So for our case, rotations are all of equal length L, so distinct rotations would lead to different states. So marking visited states ensures we count each distinct rotation only once. In case of periodic x, some rotations are identical, they will map to the same state, and we add only once.
Thus the algorithm yields the correct answer.
Complexities: building SAM O(|s|). For each query, O(|x|) time. Since total length of queries <= 1e6, overall O(|s| + total queries length) which is about 2e6, very efficient.
Memory: SAM with up to 2*|s| states (~2e6). Each state has array of 26 transitions (or map). Since alphabet is 26, we can store fixed-size array of ints (maybe 26 integers per state) but that would be 2e6 * 26 * 4 bytes = 208 MB (maybe borderline but can be optimized using map/dict). In C++ typically they use array of size 26 only for states, but memory might be high (2e6*26 ~ 52 million integers, 4 bytes each = 208 MB, which is okay? Usually memory limit maybe 256 MB. However Python would be heavy. But we are just describing solution; implementation in C++ typical.
Alternatively, use map (unordered_map) per state to store only used transitions, reducing memory but increasing time. Since alphabet is small (26), using array is fine.
Now we need to ensure the algorithm counts correctly: cnt[state] is the number of occurrences (endpos size) of the substrings represented by that state. But careful: In suffix automaton, the number of occurrences of a substring corresponds to the number of starting positions? Actually endpos size gives the number of ending positions of the substring. For a given string t of length L, its occurrence count in s is the number of positions i such that s[i-L+1..i] = t. That's exactly the size of endpos set for t. So cnt[state] after propagation gives the number of occurrences of each substring represented by that state. However, for a specific string t (like a rotation), the state that we locate using traversal (after adjustment) indeed corresponds to the equivalence class containing t. So its cnt gives the number of occurrences of t. Good.
But there is a nuance: The automaton's cnt after propagation gives the number of occurrences of each substring represented by that state. However, each state represents several substrings (those with lengths in [minlen, maxlen]), but they all share the same occurrence count? Actually in SAM, all substrings in a state have the same endpos set, so they occur exactly at the same set of ending positions. Therefore, cnt[state] is the number of occurrences for any substring represented by that state. So even if we locate the state that contains t (which we ensure that t's length L is within [minlen, maxlen]), then cnt[state] gives the number of occurrences of t, since t is one of the substrings in that state. Good.
Now we need to be careful: When we adjust state by moving up until len[link] < L, we ensure that L is within the state's interval. This gives us the state that actually contains substrings of length L. However, it's possible that after adjustment, the state's minlen <= L <= maxlen, but the specific string t (the rotation) might not be in that state? Actually, if we arrived at the state by following the characters of t (the current suffix), then the suffix we have matched is exactly the last L characters (if curLen >= L). The state we are in after reading the whole prefix (and possibly after moving up) is the state that represents the entire matched suffix (the suffix of the processed prefix). The string that is the suffix of length L is a substring of that matched suffix; it is represented by the state we find after adjusting. Since we moved up to the state whose maxlen >= L and link's maxlen < L, that state contains the substring of length L (because the set of substrings in the state includes all suffixes of the longest string in that state that have length > link.maxlen). Since the matched suffix (which is the longest represented by the original state) has the suffix of length L, and after moving up we ensure that the length L is within the interval, the substring of length L is indeed in that state. So it's correct.
Edge Cases: When curLen == L but we haven't adjusted, we still need to adjust if len[link] >= L. For example, suppose the current state has len = L, but its link has len also L? That can't happen because link's len is strictly less than state's len. But link's len could be L-1 or less. So len[link] < L normally. So adjustment might not be needed when curLen == L. But what if the state's len > L and we didn't