Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i.
Constraints
1 ≤ length of T ≤ 1000000
1 ≤ length of P_i ≤ 1000
1 ≤ Q ≤ 10000
The
input consists of alphabetical characters and digits
Input
In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively.
Output
For each question, print 1 if the text includes P_i, or print 0 otherwise.
Example
Input
aabaaa
4
aa
ba
bb
xyz
Output
1
1
0
0
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are asked to solve a string matching problem: Given a long text T (up to 1e6) and up to Q=10000 queries, each pattern P_i length up to 1000. We need to answer whether P_i appears as a substring in T. Output 1 if yes else 0.
Constraints: T length up to 1e6, Q up to 10000, each pattern length up to 1000. Total length of all patterns could be up to 10^7 (10000*1000). That's moderate. We need an efficient way to answer many substring queries.
Standard approach: Build a suffix array or suffix automaton (SAM) or a trie of all suffixes? Since T is fixed and queries are many, we can preprocess T to answer substring queries quickly. Options:
Build a suffix array with LCP and binary search for each pattern O(|P| log |T|). With Q up to 10k and pattern length up to 1000, log 1e6 ~20, so total about 2e8 char comparisons worst-case? Actually binary search would compare strings, each comparison could take O(|P|) time in worst case, so per query O(|P| log |T|) ~ 1000*20 = 20000, times 10k = 2e8, which might be borderline but possible in C++ with optimization, but might be okay? But we can do better.
Build a suffix automaton (SAM) which can test membership in O(|P|) per query after O(|T|) preprocessing. That's ideal: O(|T| + sum|P_i|). Sum of |P_i| up to 10^7, which is fine. So implement SAM.
Alternatively, build a hash (e.g., rolling hash) for T and answer queries by checking if any substring hash matches. But with multiple queries, we could precompute all hashes of all possible lengths? Pattern lengths vary up to 1000, and T up to 1e6, storing all substrings would be O(|T|*maxLen) which is too large. But we could use rolling hash and for each pattern compute its hash and then slide over T's windows of same length? That would be O(|T|) per query, too slow.
Thus SAM is good.
Implement SAM: each state has next[?] transitions for characters. Characters are alphanumeric (digits and letters). That's 62 possibilities. We can use map (balanced tree) or array of size 62. Since total transitions in SAM can be up to 2*|T|, using map might be slower but okay. However, we could convert characters to small integers (0-61). For performance, using unordered_map or array of size 62 (if memory permits: 2*1e6 * 62 ~ 124 million entries, too big if using array). So map is fine: each state has std::map<char, int> next.
Implementation details:
SAM states: struct State { int len, link; map<char,int> next; }; Initialize with state 0 (root) having len=0, link=-1.
Extend SAM for each character of T.
Then to check pattern P: start at state 0, follow transitions for each character; if at any step no transition, answer false. If all processed, then pattern exists.
But careful: SAM built for T will accept exactly all substrings of T. So this works.
Complexities: Building SAM O(|T|) time with map operations O(log sigma) per char. Checking each pattern O(|P|) with map lookups.
Total states ~ 2*|T| = 2e6, which is okay memory-wise (each state has map and two ints). But map overhead could be high: 2e6 states each with a map, that would be huge memory (each map object has overhead). Actually typical SAM implementation uses vector<map<char,int>> but number of states is at most 2*|T| = 2e6, which is large. For |T|=1e6, states ~2e6. Each state having a map (even empty) would be huge (like 2e6 * (size of map) maybe 40 bytes? That's 80 MB plus transitions). Actually each state's map will contain only transitions from that state. The total number of transitions in SAM is O(|T| * sigma?) Actually for SAM, the total number of transitions is bounded by 2|T|? Not exactly; typical SAM has at most 3|T| transitions? The number of edges is O(|T| * sigma) worst-case if sigma is large? But with a fixed alphabet, the number of edges is O(|T| * alphabet size) only in suffix tree, but SAM compresses so number of edges is at most 2|T|-2? Wait: In SAM, each state can have multiple outgoing edges. The total number of edges is O(|T| * alphabet size) in worst case? Actually SAM is a directed acyclic graph; it can have up to O(|T| * alphabet) edges? I recall that the number of transitions in a SAM is O(|T| * alphabet) in the worst case, because it's essentially a suffix trie compressed. But it's known that the number of transitions in a SAM is at most 3|T|? Let's think: In the construction algorithm, each iteration adds at most 2 states and a few transitions. The total number of transitions is at most 2|T| - 2? I'm not entirely sure. Let's consider the suffix automaton of a string of length n: it has at most 2n-1 states and at most 3n-4 transitions (for n>1) according to some sources. Actually I recall that the number of transitions in a SAM is linear in n: at most 3n-4 for n>=3. Yes, the number of edges (transitions) is O(n). So the total number of entries across all maps is O(n). So storing them as map per state is okay: each map will hold only few entries on average. But each state object still contains a map object (which is an empty container if no transitions). That overhead per state could be significant: std::map typically has a size of 24-48 bytes (depending on implementation). For 2e6 states, that would be ~100 MB just for map objects. Plus the transitions stored in map nodes (each node also overhead). Might be borderline but possibly okay? But memory limit? Not specified, but typical OJ might have 256 MB or 512 MB. Let's estimate: 2e6 states, each state with two ints (len, link) = 8 bytes, plus a map object. In gcc, std::map is often 24 bytes (three pointers). So 2e6 * 24 = 48 MB. Plus each transition stored: total transitions O(3n) = 3e6, each transition stored as a map node with key and value, plus pointers for tree. Each node might be about 32-40 bytes. 3e6 * 40 = 120 MB. So total maybe ~200 MB. Might be high but could be okay if memory limit is 512 MB. However, we can reduce memory by using unordered_map? That might have similar overhead. We can also use array of vectors for transitions? Since alphabet size is 62, we could store transitions as a fixed array of 62 ints, but that would be huge: 2e6624= ~496 MB for int array. That's too much.
Alternatively, we could build a suffix array with LCP and answer queries by binary search with O(|P| log n) but that would be slower but less memory. However, we might optimize by using suffix automaton but using a more compact representation: For each state, we can store a vector of pair<char,int> and use binary search or use sorted list because transitions per state are limited. However, we still need to be able to find transition for a character quickly. We could store a map, but we can also store a plain C array of pointers? Since alphabet size is only 62, but number of states is large; using an array of 62 ints per state is too memory heavy. So we can store transitions as a map.
Another approach: Use Aho-Corasick? That would require building a trie of all patterns and then scanning T once, marking which patterns appear. That's also efficient: O(total length of patterns + |T| + total matches). But we need to answer queries individually, we can mark each pattern's occurrence. Since patterns are up to 1000 each, total length up to 10^7, building AC automaton with that total length is feasible (trie nodes up to 10^7, which is large but possibly okay? 10^7 nodes each with map or array of 62? That's even bigger memory than SAM. So not good.
We could also build a suffix array with LCP and then for each pattern do binary search. With careful implementation using std::string_view or pointer comparisons might be fast. Let's evaluate: For each query, we need to compare the pattern with a suffix (starting at some position) in T. That can be done using strncmp? In C++ we can compare by iterating characters. Complexity: binary search does about log2(1e6) ≈ 20 comparisons, each comparison could scan up to length of pattern (1000) in worst case, so 20,000 char accesses per pattern, times 10,000 = 200 million char accesses. That's 200 million, which is okay in C++ within time limit if optimized (maybe 0.2 seconds per 10 million? Actually 200 million char comparisons might be ~0.2 seconds? Depends, but 200 million operations might be around 0.5-1 second in modern CPU, possibly okay. But there is overhead of binary search and indexing. However, we need to build suffix array: O(n log n) with n=1e6, which is okay but might be memory heavy: storing suffix array as vector of size 1e6 (4 MB). Also we need to store T. So memory is fine.
But we need to answer queries quickly; 200 million char comparisons is acceptable if the time limit is not too strict (like 2 seconds). But we need to also consider worst-case patterns that cause many character comparisons. However, we can improve by using LCP to accelerate binary search? Actually the typical approach: for suffix array, to search pattern, we use two binary searches (lower bound) comparing pattern with suffix. That's O(|P| log n). Using LCP can reduce to O(|P| + log n) but more complex.
Given simplicity, we could implement suffix array with binary search. But we must ensure we don't exceed time. However, there is also possibility of many patterns with length 1000, and T length 1e6, and pattern comparisons may early exit often. In worst-case scenario, pattern matches many suffixes? Actually when comparing pattern to a suffix, we compare up to min(|P|, length of suffix) characters until mismatch or end. In binary search, the compared suffixes vary. For random strings, mismatches often occur early. So average char comparisons per query might be less. But worst-case could be if T consists of all same character, e.g., 'a'*1e6, and patterns are also 'a'*1000, then each comparison will compare up to 1000 characters because both strings are same for first 1000 characters? Actually for suffix array of T all 'a', the suffixes are all 'a'*something. Comparing pattern 'a'*1000 with a suffix of length L (>=1000) will compare all 1000 characters because they are all equal. So each comparison will compare 1000 characters. Then binary search will compare 20 times => 20,000 per query, times 10,000 = 200 million char comparisons. That's still maybe okay. However, we also need to ensure the implementation is efficient: we should avoid copying substrings, use pointer or string_view, compare directly.
But there is also the suffix array construction time: O(n log n) with n=1e6. That's okay with efficient algorithm like SA-IS (linear) or doubling. Doubling would be O(n log n) with n=1e6: log2(1e6) ~20, so 20 * n = 20e6 operations, which is okay. However, implementing doubling algorithm might be nontrivial but doable. But we also need to handle alphanumeric characters; we can map to integer ranks.
Alternative: Build a suffix array using the built-in C++ sort? That would be O(n^2 log n) if we sort strings? Not.
Thus either SAM or SA.
Given constraints, I think SAM is elegant and linear. But memory could be high. Let's check typical SAM memory usage in C++ with map: For n=1e6, states up to 2e6, but in practice for random strings, number of states is close to 2n? Actually worst-case is 2n-1 for a string of distinct characters? The worst-case number of states is 2n-1 for strings like "abcde...". For random, it's around 2n. So 2e6 states. That many map objects? Actually we can allocate states in a vector, each state has map. In C++, each map is an independent object. That could be huge because each map has at least three pointers (typically 24 bytes) plus maybe an allocator. 2e6 * 24 = 48 MB. That's fine. But also each state has len and link ints => 8 bytes, total 56 MB. Then plus the transition nodes: For each edge, map node contains key, value, pointers, color, etc. Typically a node in std::map (red-black tree) has left, right, parent pointers, color, and key, value. So maybe 32-48 bytes per node. The number of edges is about 3n = 3e6. So edges memory = 3e6 * 40 ≈ 120 MB. So total ~176 MB. That's within 256 MB likely. But we also need to store T and queries etc. Could be close but okay.
But we must also consider overhead of vector with dynamic allocation. Using vector where State is a struct with map, the map objects are stored inline, so the vector's buffer holds the maps. That buffer would be large: each State size = sizeof(map) + 2sizeof(int) + padding. In typical 64-bit gcc, sizeof(std::map) = 48? Let's check: I've seen it's 48 bytes. Actually on many implementations, std::map is 48 bytes (86). Let's assume 48. Two ints 8 bytes, alignment might cause size to be 56? Possibly 56. So 2e6 * 56 = 112 MB. Plus edges 120 MB => 232 MB. Might be okay if memory limit is 512 MB. But if limit is 256 MB, it might be tight but still maybe under 256. However, we also have T (1e6 bytes ~ 1 MB) and queries (total 10^7 chars ~ 10 MB) and some other overhead. So total maybe 250-300 MB. Could be okay. But depends on the judge.
We can reduce memory by using unordered_map? That might have lower overhead per entry? Unordered_map node includes key, value, hash, next pointer, maybe 32 bytes per node? And the bucket array overhead. But map's node includes three pointers and color flag, similar size. Actually unordered_map node includes key, value, and next pointer, maybe plus hash stored? Usually it's key, value, next pointer. So about 24-32 bytes. Might be similar. However, unordered_map's bucket array adds memory. So map is fine.
But maybe we can use a more memory efficient SAM: store transitions as a sorted vector and use binary search for lookup, because number of transitions per state is small (most states have few outgoing edges). However, we need dynamic addition during construction. The SAM construction algorithm needs to add transitions to new states and clone states. Using sorted vector and later sorting might be tricky because we need to add transitions one by one and also copy transitions when cloning. It's easier to use map.
Given typical CP problems, implementing SAM with map for n=1e6 is common and accepted. I've seen problems where n up to 1e6 and SAM passes.
But we need to be careful with stack recursion? Not needed.
Let's proceed with SAM.
But note: The input characters are alphabetical characters and digits. So uppercase, lowercase letters and digits? Probably both. That's 26+26+10=62. So we need to handle all.
Implementation steps:
Read string T (no spaces, but could be alphanumeric, maybe read using std::getline). The first line includes T. It could be up to 1e6 characters. Use getline.
Build SAM:
Data structures: vector of struct { int len, link; map<char,int> next; }.
Initialize: state 0: len=0, link=-1, next empty.
last = 0.
For each character c in T:
create cur state with len = last.len + 1.
int p = last;
while p != -1 and next[p].find(c) == next[p].end():
set next[p][c] = cur;
p = link[p].
if p == -1: link[cur] = 0.
else:
int q = next[p][c];
if len[p] + 1 == len[q]: link[cur] = q.
else:
clone state: create new state with len = len[p] + 1, link = link[q], next = next[q] (copy).
while p != -1 and next[p][c] == q:
next[p][c] = clone;
p = link[p].
link[q] = link[cur] = clone.
last = cur.
After building, for each query pattern P:
Start at state 0.
For each char c in P:
if next[state].count(c) == 0: output 0; break.
else state = next[state][c].
If completed loop, output 1.
That's it.
Complexities: Building SAM O(|T| * log sigma). Checking O(sum|P| * log sigma). With sigma up to 62, log sigma ~6, total operations maybe 6e6 for building + 6e7 for queries? Actually sum|P| up to 10^7, each lookup is map find O(log sigma) ~6, so 60 million map operations, which is okay.
Potential pitfalls: Large memory usage. Use global vectors and reserve capacity. We can estimate number of states: at most 2*|T|. So we can reserve 2*|T|+5.
But careful: When cloning, we need to copy the map of q. Copying map could be expensive if done many times, but total number of clones is O(n) and each copy copies the entire map of the original state. However, each edge will be copied at most a few times? In SAM construction, each state's map may be copied when cloning. In worst case, total copies could sum to O(n * sigma)? Actually, each edge can be copied during clone operations. Since the total number of edges is O(n), the total copying cost is O(n) edges across clones. Because each time we clone a state, we copy its map (edges). But the size of map of q is its outgoing transitions. Summed over all clones, the total number of copied edges could be O(n). For example, string of all distinct characters: building SAM results in many states each with one transition? Actually for distinct characters, each new character creates a new state and many clones? Let's think worst-case. There is known property: total number of transitions in SAM after cloning is still O(n). So copying maps might overall be O(n) edges, but each copy duplicates the entire map object, which might be heavy if many clones have large maps. But each state's outdegree is bounded by sigma, but the sum of outdegrees is O(n). So copying maps overall copies each edge at most once? Actually when we clone a state, we copy all outgoing edges of q. Those edges already exist; after cloning, the clone has same set. But later, those edges may be modified? The clone's edges are separate copy, not shared. However, the total number of edges after all operations is O(n). Initially we add edges, and when we clone we add new edges from the clone, but we also copy existing edges. So the final total edges is O(n). So the number of edge creations (including copies) is O(n). Therefore, copying maps is okay.
But careful: when we assign next[clone] = next[q] in C++, that does a deep copy of the map. That's expensive if the map is large. But each state's outdegree is typically small; in worst-case string like "aaaa...", the SAM will have a linear chain with small outdegree? Actually "aaaa...": after first character, root-> state1 with 'a'; after second, new state2, and we might create clones? For repeated characters, the SAM has only 2 states? Let's analyze: For a string of same character, the SAM has number of states = length+1? Actually for "aaaa", states: 0 (root), state1 for "a", state2 for "aa", state3 for "aaa", state4 for "aaaa"? Usually SAM for repeated characters has linear structure, with each state having one transition for 'a' to next state, plus possibly extra? So each state's map size is 1. So copying is cheap.
Worst-case for outdegree: e.g., random string might have many distinct characters, but each state's outdegree is limited by the number of distinct characters that appear after certain prefixes. Could be up to sigma. However, the average outdegree is small, but some states (like root) may have many outgoing edges, up to sigma. In the worst-case string like "abacaba..."? Actually root may have many distinct first characters. For a string with many distinct characters, root may have transitions for each character that appears. Since alphabet is 62, root's outdegree could be up to 62. That's not large. So copying maps is fine.
Thus SAM is fine.
But we also need to handle input reading efficiently: use ios_base::sync_with_stdio(false); cin.tie(0); getline.
Potential memory: For each state, we store a map. Using map, we might have many states, but as argued it's okay.
Alternatively, we could implement SAM using arrays of int for transitions with a dictionary using hashing? But map is simplest.
But note: The constraints say T length up to 1,000,000. So SAM with 2,000,000 states might be large but doable.
Let's implement.
Implementation details in C++:
We'll use vector st.
struct State { int len, link; map<char,int> next; };
We'll reserve 2*T.size().
But careful: when we use vector, the State struct's map will be moved/copied when vector resizes. That could be expensive if we don't reserve. So we reserve capacity.
We also need to dynamically add states. We'll push_back new states.
Algorithm for extend:
void sa_extend(char c) {
int cur = st.size();
st.emplace_back();
st[cur].len = st[last].len + 1;
int p = last;
while (p != -1 && st[p].next.find(c) == st[p].next.end()) {
st[p].next[c] = cur;
p = st[p].link;
}
if (p == -1) {
st[cur].link = 0;
} else {
int q = st[p].next[c];
if (st[p].len + 1 == st[q].len) {
st[cur].link = q;
} else {
int clone = st.size();
st.emplace_back();
st[clone].len = st[p].len + 1;
st[clone].next = st[q].next; // copy map
st[clone].link = st[q].link;
while (p != -1 && st[p].next[c] == q) {
st[p].next[c] = clone;
p = st[p].link;
}
st[q].link = st[cur].link = clone;
}
}
last = cur;
}
But careful: when we copy the map, we might want to use st[clone].next = st[q].next; This copies the entire map. After copying, we will modify st[q].link etc. That's fine.
We need to ensure that we reserve enough capacity to avoid reallocation after we start cloning because cloning adds an extra state inside the loop. But we can't know exactly. We can reserve 2 * T.length() + 5.
Now queries: for each pattern, we traverse SAM.
Potential pitfalls: The SAM built from T includes all substrings? Yes, exactly all substrings of T. So this works.
But we need to be careful about newline characters: After reading T, we may have to ignore newline. Use getline(cin, T) and then read integer Q. Then read Q lines of patterns.
Edge cases: Patterns could be empty? Constraints say length of P_i >= 1, so not empty.
Time for queries: For each pattern, we start from state 0 and follow edges. Using map find each char.
We should also consider that the SAM might have many states and map lookups may be somewhat slower, but still okay.
Alternative: Use an array of size 128 for transitions, but that would be too big per state. But we can use unordered_map with custom hash. However, map is fine.
We should test with the example.
Now about memory: Suppose T length = 1,000,000. Then max states = 2,000,000. Each State: int len (4), int link (4), map<char,int> next. In typical libstdc++, std::map is 48 bytes on 64-bit? Let's check: On my system, sizeof(std::map<char,int>) = 48. With padding, total struct size maybe 56 (since ints 4+4=8, map 48, alignment 8? Actually struct size might be 56 because map alignment 8? Let's compute: 8 bytes for ints (maybe padded to 8 because next may require 8-byte alignment). Typically the compiler will align map to 8 bytes, so struct size = 8 (ints) + 48 (map) = 56. So 2e6 * 56 = 112 MB. Then each map entry: each edge stored as a node in the map's red-black tree. Number of edges: up to about 3e6. Each node might be something like 40 bytes. 3e6 * 40 = 120 MB. Total ~232 MB. That's okay if memory limit is >=256 MB. If limit is 128 MB, that would be too high. Many judges have 256 MB for C++.
But note: The problem could be from an old contest (maybe JOI?) with typical memory limit 1024 MB? Not sure. However, we can also implement a suffix array approach to be safe memory-wise.
Let's consider suffix array approach memory: We need to store T (1 MB), suffix array (4 MB if int), maybe rank array (4 MB) for construction, LCP? Not needed for search. So total <10 MB. That's tiny. And time: O(n log n) construction (maybe 1e6 * log2(1e6) = 20e6) plus queries 200 million comparisons. Could be borderline but might be acceptable in 2 seconds? 200 million char comparisons might be ~0.2 seconds if optimized? Actually 200 million operations could be about 0.5-1 second on modern CPU, plus construction overhead, total maybe <2 seconds. However, in worst-case pattern and T all 'a', each comparison will compare 1000 characters before determining order? Actually in binary search we compare pattern to suffix at mid. In an all-'a' string, all suffixes are equal in the first 1000 characters? Actually suffixes differ in length. The pattern "a"*1000 is compared with a suffix that may be shorter than 1000? For suffix array of all 'a's, the suffixes are sorted by length because all characters same, and the usual comparison would treat shorter string as smaller if it's a prefix. So when comparing pattern "a"*1000 (length 1000) with a suffix of length L, if L >= 1000, then the first 1000 characters are all 'a', so they compare equal, and then we need to see which is longer? Actually string comparison in lexicographic order: after comparing the first min(len1, len2) characters, if they are equal, the shorter string is considered smaller. So for pattern "a"*1000 vs suffix of length L (L >=1000), we compare 1000 characters (all equal) then pattern length is 1000 and suffix length is L, since 1000 < L, pattern is considered smaller than suffix. For suffix with L < 1000, after L characters equal, pattern has extra characters, so pattern is larger. So each comparison will scan up to min(1000, L) characters. In worst case, when comparing with a suffix of length exactly >=1000, we scan 1000 characters. So binary search still does 20 full scans of 1000. So 20k per query. So total 200 million char accesses. That's fine.
But we need to implement suffix array efficiently. We can use the O(n log n) doubling algorithm with integer ranks. Complexity O(n log n) with n=1e6, 20 iterations each O(n) = 20e6, plus sorting each iteration? Wait the typical doubling algorithm: we sort by pair (rank[i], rank[i+k]) using counting sort (radix sort) to achieve O(n log n) but with counting sort it's O(n) per phase if using bucket sort based on ranks (which are up to n). That is doable. But implementing radix sort (two passes) might be a bit involved. However, we could use std::sort with pairs; each iteration we sort n elements, which is O(n log n) per iteration, leading to O(n log^2 n) which for n=1e6 is 1e6 * 400 ~ 400 million operations, could be heavy but maybe still pass? Let's compute: log n ~20, n log n ~20e6, times log n again ~20e6*? Actually typical suffix array using std::sort with pair<int,int> does O(n log^2 n) comparisons; each comparison of two pairs is O(1) but there are O(n log n) comparisons? Actually sort takes O(n log n) comparisons per phase, and there are O(log n) phases => O(n log^2 n). For n=1e6, log n ~20, n log^2 n = 1e6 * 400 = 400 million comparisons, each comparison cheap. That could be borderline but maybe okay in C++ with optimizations. However, the constant factor for sorting 1e6 elements 20 times is large; each sort might allocate temporary vectors, etc. I think it might be too slow.
But we can improve: Use SA-IS linear time suffix array? That's more complex. Or we can use suffix array construction via SA-IS from library? Not allowed.
Alternatively, we can use a suffix array built with the algorithm that sorts suffixes by the first k characters using counting sort: radix sort by second key then first key. That's O(n) per phase. I've implemented before. For n=1e6, 20 phases, 20e6 operations, fine.
Given the memory concerns of SAM, I'd lean toward implementing SA with linear-time per phase (counting sort) because it's simpler to code? Actually the counting sort implementation is a bit longer but doable.
But perhaps we can use a simpler approach: Build a suffix array using the built-in sort on indices with custom comparator that compares substrings using the precomputed rank from previous doubling step. That's typical:
vector sa(n), rank(n), tmp(n);
for i: sa[i]=i, rank[i]=T[i]
k=1; while k<n: sort(sa.begin(), sa.end(), [&](int i, int j){ return rank[i]!=rank[j]? rank[i]<rank[j] : rank[i+k < n ? i+k : -1] < rank[j+k < n ? j+k : -1]; }); then compute tmp[sa[0]]=0; for i from 1: ...; swap(rank,tmp); k*=2; }
The sort uses comparator that compares pairs of integers. Sorting 1e6 elements 20 times: each sort O(n log n) ~ 20e6 comparisons per sort? Actually n log n for 1e6 is about 20e6 comparisons. Times 20 sorts gives 400 million comparisons. Each comparison involves two array lookups and integer comparisons, which is cheap. 400 million operations might be okay within a couple seconds if optimized? Possibly but not guaranteed. I'd rather implement counting sort to be safe.
But there is another approach: Use a suffix automaton but with array of size 62 for transitions if we compress state count? Actually number of states is up to 2e6, each with array of 62 ints (maybe using short int?). That would be 2e6 * 62 * 4 = 496 MB, too large. Could use uint32_t but still huge. Could use vector for each state? No.
Maybe we can reduce SAM memory by using a single global map from pair (state, char) to next state, i.e., storing transitions in a hash table per state? That would be similar.
Another idea: Build a suffix array using the algorithm that sorts suffixes by the first 2 characters, then 4, etc., but using bucket sort (radix sort). I have implementation ready.
Given that sum of pattern lengths is up to 1e7, we could also build a hash set of all substrings? Not feasible.
Another approach: Build a trie of all suffixes? That would be a suffix trie, which has O(n^2) nodes, too big.
Thus either SAM or SA.
Let's think about SAM memory more precisely. In typical CP solutions for problems with n=1e6, SAM is often used with map and passes. I've seen problems like "Substrings" SPOJ NSUBSTR where n=250000 and SAM with map passes. For n=1e6, maybe it's still okay. But we need to ensure we use efficient memory.
One trick: Use arrays of vectors to store transitions? For each state, we could store a vector<pair<char,int>> and then for lookup we can binary search because per state number of transitions is small. During construction, we need to add transitions and also clone. Insertions into a sorted vector can be done using binary search and insert, which is O(k) due to shifting. But number of transitions per state is small (average maybe <3), so O(k) insertion is fine. But we also need to copy vectors during clone. That would also be small. However, we need to support lookup by char quickly; we can keep the vector sorted and use binary search (O(log d)). That's okay. The overhead of vector per state: each state has a vector object (3 pointers: start, end, capacity) which is 24 bytes. That's similar to map. But the vector's elements are stored contiguously; each element is a pair<char,int> maybe 8 bytes (char padded? Actually pair<char,int> likely 8 bytes (char + int + padding to 4? Actually typical sizeof(pair<char,int>) = 8 due to alignment). So total edges stored in vectors: total edges O(n) so about 3e6 * 8 = 24 MB, plus pointers in vector (overhead per state). That's much less than map's node overhead (40 bytes per edge). So using sorted vectors could drastically reduce memory.
But we need to support dynamic insertion and cloning. Insertion into sorted vector for each addition of transition: When we add a transition from state p to cur during extension, we need to insert a char-int pair into the vector of state p. Since during SAM construction, we may add many transitions to states (potentially many). But the number of transitions added is O(n). Insertion into a sorted vector of size d costs O(d) to shift elements. But d is small (average outdegree small). So overall could be acceptable. But we need to keep the vector sorted to allow binary search lookup. For lookup we can use lower_bound.
Also during cloning, we need to copy the vector of transitions from q to clone. That is O(outdegree(q)) time.
Thus the total time might increase slightly but still O(n * average degree) which is O(n * sigma?) But average outdegree is small, and sum of outdegrees is O(n). So total shifting cost across all insertions could be sum of squares of outdegree? Actually each insertion into a state's vector shifts the later elements. If we insert in order, and we add edges one by one to each state, the total cost per state is O(d^2) where d is its outdegree. Since d can be up to sigma (62), that's at most 62^2=3844 per state, which is small. And number of states is 2e6, worst-case total could be large if many states have high outdegree. However, typical SAM states have low outdegree. In worst-case, root may have outdegree sigma, and some other states may also have high outdegree. But sigma is only 62. So the worst-case cost per high-outdegree state is O(62^2) = ~4000, and there may be O(n) such states? Not; only a few states have high outdegree. Actually, in a SAM, each state corresponds to a set of end positions, and the outdegree is limited by the number of distinct characters that appear after those substrings. In worst-case, if the string is random over alphabet of size 62, many states may have outdegree around something like expected number of distinct next characters. Could be small. Actually, for random string, the expected outdegree per state is small. So overall time should be okay.
Thus using vectors for transitions could be more memory-efficient and possibly faster due to cache locality. Let's consider memory: each state: two ints (8 bytes) + vector (typically 24 bytes) = 32 bytes? Actually vector has three pointers: start, end, capacity (8 each) => 24 bytes on 64-bit. So 8+24 = 32, plus alignment? Possibly 32 or 40? That's 32 bytes. So for 2e6 states => 64 MB. The vector's storage for edges: each edge is pair<char,int>. If we store char and int, size might be 8 bytes (char padded to 4? Actually pair<char,int> may be 8 due to alignment). With 3e6 edges => 24 MB. So total memory ~88 MB. That's much better than map's 232 MB. Good! So we can implement SAM with sorted vectors.
But we need to be careful: The vector for each state might be empty, but still each state has a vector object (24 bytes). 2e6 * 24 = 48 MB. Plus ints = 8 MB? Actually ints 24 =8 bytes each state? 2e68=16 MB. So total 64 MB for state objects? Wait recalc: struct State { int len, link; vector<pair<char,int>> next; }; sizeof(vector) is 24 (typical). The two ints are 8 bytes, but due to alignment the struct size might be 8+8? Actually compiler may pad to align vector's pointer to 8 bytes. So the struct may have int len (4), int link (4), then vector (24) -> total 32? Actually if we have two ints (8 bytes) followed by vector (24), the total size is 32 bytes, because the ints occupy 8 and vector starts at offset 8, which is aligned. So 32 bytes per state. 2e6 * 32 = 64 MB. Then edges: each edge pair<char,int> likely 8 bytes (since char is 1, int 4, padding 3? Actually typical pair<char,int> size is 8 due to alignment to 4? In many compilers, pair<char,int> is 8. So 3e6 * 8 = 24 MB. Additional overhead: vector's dynamic allocation for edges: each vector's capacity may be slightly larger than size, but overall negligible. So total ~90 MB. That's great.
Thus we can implement SAM with vector of sorted transitions.
Implementation details:
We need to support operations:
Add transition: For state p and char c to state cur. We need to insert (c, cur) into next[p] while maintaining sorted order (by char). Since we will be adding transitions in increasing order of characters? Not guaranteed; characters are from input, but they may appear in any order. However, we can simply insert at the end and sort later? But lookup during construction (while extending) needs to check if transition exists. So we need to check if there's already a transition for char c. With sorted vector, we can use binary search (lower_bound). Then if not found, we insert (c, cur) at the correct position (using vector insert). This is O(d) due to shifting. Since d is small, that's fine.
Clone state: we need to copy the vector of transitions from q to clone. That is easy: next[clone] = next[q]; (makes a copy). Then we may need to modify some transitions later? Actually after cloning, we will adjust some transitions from p states to point to clone. Those modifications involve updating existing transitions: we need to change the target of transition for character c from q to clone. In the while loop: while p != -1 && next[p][c] == q: set next[p][c] = clone. To do this with vector representation, we need to locate the transition for char c in state p and change its target. Since we know that there is a transition for c, we can find it via binary search and then modify the int. This is O(log d). So fine.
During extension, we also need to find if transition exists: while p != -1 && !has_transition(p, c): set transition; else break. So we need a function has_transition(p,c) that returns true and also returns the target if exists. We can implement a function get_transition(p,c) that returns -1 if not found, else the state.
So overall doable.
One more thing: During the while loop where we add transitions for all p that lack transition, we may add many transitions to the same state p? Actually each iteration adds a transition to state p for character c. That's a new transition, so we insert into the vector of p. Since we are iterating p along suffix links, the order of addition might be such that characters are same? But the same state p may have many transitions added over time. However, each state's transitions are built gradually; we need to keep them sorted. We can simply insert in the correct position using binary search to find insertion point and then vector.insert(iterator, pair). This is O(d) per insertion. Summed over all insertions (total transitions O(n)), total shifting cost is sum of squares of outdegree per state. As argued, it's manageable.
Alternatively, we could keep the vector unsorted and sort only when needed for binary search, but we need binary search for lookups often (for each step of while loop and later for queries). So better keep sorted.
But we could use a small array for states with few transitions: For state with outdegree <= some threshold, we could use linear search instead of binary search. But for simplicity, we can use binary search.
Now memory: We'll allocate vector st. State can be defined as:
struct State {
int len, link;
vector<pair<char, int>> next;
};
void extend(char c) {
int cur = st.size();
st.emplace_back();
st[cur].len = st[last].len + 1;
int p = last;
// Add transition from p to cur for c if not exist
while (p != -1 && !has_transition(p, c)) {
add_transition(p, c, cur);
p = st[p].link;
}
if (p == -1) {
st[cur].link = 0;
} else {
int q = get_transition(p, c);
if (st[p].len + 1 == st[q].len) {
st[cur].link = q;
} else {
int clone = st.size();
st.emplace_back();
st[clone].len = st[p].len + 1;
st[clone].next = st[q].next; // copy vector
st[clone].link = st[q].link;
// Redirect transitions from p and its suffix links that point to q to point to clone
while (p != -1 && get_transition(p, c) == q) {
set_transition(p, c, clone);
p = st[p].link;
}
st[q].link = st[cur].link = clone;
}
}
last = cur;
}
Now we need to implement has_transition, get_transition, add_transition, set_transition.
Since we keep vector sorted by char, we can use lower_bound.
Helper:
int get_next(int state, char c) {
auto& vec = st[state].next;
auto it = lower_bound(vec.begin(), vec.end(), make_pair(c, -1));
if (it != vec.end() && it->first == c) {
return it->second;
} else {
return -1;
}
}
For add_transition(state, c, target): we need to insert if not already present. But we call add_transition only when we are sure it's not present. So:
void add_transition(int state, char c, int target) {
auto& vec = st[state].next;
auto it = lower_bound(vec.begin(), vec.end(), make_pair(c, -1));
// it points to first element >= c; we know it doesn't have c because we checked earlier, but just in case we can assert.
vec.insert(it, {c, target});
}
For set_transition(state, c, newtarget): we need to update existing transition. We'll find it and modify.
void set_transition(int state, char c, int newtarget) {
auto& vec = st[state].next;
auto it = lower_bound(vec.begin(), vec.end(), make_pair(c, -1));
// it should exist and it->first == c
it->second = newtarget;
}
Also has_transition can use get_next.
Now we must be careful: get_next uses lower_bound, which requires the vector to be sorted. We'll maintain sorted order by always inserting in correct position. When we copy vector (during clone), the copy will be sorted because original is sorted.
Now we need to ensure that after we clone, we might need to add more transitions to the clone? Actually we copy the transitions from q, so it's already sorted. Later, we may add transitions to the clone? Not directly; but during further extensions, we might add transitions to any state, including clones, via add_transition. That will maintain sorted order.
Now about performance: Using lower_bound with vector of pairs for each lookup. For states with small outdegree (like 1-5), linear scan could be faster due to cache, but binary search is fine. However, we can also implement a small inline linear search for small vectors to reduce overhead. But not necessary.
Now building SAM with vectors may be slower than map due to insertion shifting overhead. But memory wise it's better.
Given the constraints (1e6 length, 1e4 queries), both approaches should pass. I'll choose the vector-based SAM for memory efficiency.
Now test on example.
We need to handle alphanumeric characters. So char range: digits '0'-'9', uppercase 'A'-'Z', lowercase 'a'-'z'. That's within ASCII.
Now code:
#include <bits/stdc++.h>
using namespace std;
struct State {
int len, link;
vector<pair<char, int>> next;
};
class SAM {
public:
vector st;
int last;
code
SAM() {
st.reserve(2000005); // enough for 2*1e6
init();
}
void init() {
st.clear();
st.emplace_back();
st[0].len = 0;
st[0].link = -1;
last = 0;
}
int get_next(int state, char c) {
auto& vec = st[state].next;
// binary search
auto it = lower_bound(vec.begin(), vec.end(), make_pair(c, -1));
if (it != vec.end() && it->first == c) return it->second;
return -1;
}
void add_transition(int state, char c, int target) {
auto& vec = st[state].next;
auto it = lower_bound(vec.begin(), vec.end(), make_pair(c, -1));
vec.insert(it, {c, target});
}
void set_transition(int state, char c, int target) {
auto& vec = st[state].next;
auto it = lower_bound(vec.begin(), vec.end(), make_pair(c, -1));
// it must exist
it->second = target;
}
void extend(char c) {
int cur = st.size();
st.emplace_back();
st[cur].len = st[last].len + 1;
int p = last;
while (p != -1 && get_next(p, c) == -1) {
add_transition(p, c, cur);
p = st[p].link;
}
if (p == -1) {
st[cur].link = 0;
} else {
int q = get_next(p, c);
if (st[p].len + 1 == st[q].len) {
st[cur].link = q;
} else {
int clone = st.size();
st.emplace_back();
st[clone].len = st[p].len + 1;
st[clone].next = st[q].next; // copy transitions
st[clone].link = st[q].link;
while (p != -1 && get_next(p, c) == q) {
set_transition(p, c, clone);
p = st[p].link;
}
st[q].link = st[cur].link = clone;
}
}
last = cur;
}
bool contains(const string& pat) {
int state = 0;
for (char c : pat) {
state = get_next(state, c);
if (state == -1) return false;
}
return true;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
code
string T;
getline(cin, T);
SAM sam;
for (char c : T) {
sam.extend(c);
}
int Q;
cin >> Q;
cin.ignore(); // to skip newline after Q
for (int i = 0; i < Q; ++i) {
string P;
getline(cin, P);
cout << (sam.contains(P) ? '1' : '0') << '\n';
}
return 0;
}
Check: For each pattern, we use contains which calls get_next per char. get_next uses binary search. That's fine.
Potential improvements: we could store next as vector<pair<char,int>> and use a custom binary search function that is inlined. That's fine.
One thing: In the while loop of extend, we call get_next(p, c) to check existence. Then if not exist, we add_transition(p,c,cur). That's fine. However, after we break from while due to existence, we may call get_next again to get q. That's okay.
Now we must consider that during the while loop, we may modify transitions of p (adding) and then later we might need to get_next(p,c) again for cloning. But after we exit while, p is the state where we found transition (or -1). That's fine.
Now test with example: T="aabaaa". Build SAM and query. Should output correct.
One potential bug: When we clone, we copy st[q].next. That copies the vector, which may be large. But it's fine.
Now memory: We reserve 2e6+5 states. st will contain state objects; each time we add states, we emplace_back, which constructs a State with default vector (empty). That's okay.
But note: In the extend function, we add two states sometimes: one cur and possibly one clone. That's why we reserved 2*n.
Edge Cases: Input patterns may be longer than T, but contains will just fail early.
Now we need to be careful about reading input: The first line contains T, may have spaces? The constraints say alphabetical characters and digits, so no spaces. So getline works fine.
After reading T, we read Q using cin >> Q. Then we need to read Q patterns, each on a line. After cin >> Q, there's a newline; we call cin.ignore() to consume it before getline. Patterns may be empty? Not per constraints.
Now about performance: The SAM construction involves many get_next and add_transition calls. For each character of T (1e6), we do a while loop that travels along suffix links. In worst-case, the total number of operations in while loops is O(n) amortized? Actually SAM construction is linear, O(n). With map it's O(n log sigma). With vector and binary search, each while iteration may have get_next (binary search) and add_transition (insert). The number of total transitions added is O(n). The number of total get_next calls is also O(n). So overall O(n log sigma) due to binary search? Actually binary search in vector of size d is O(log d) which is O(log sigma) ≤ log 62 ~6. So O(n log sigma). That's fine.
But we need to consider the cost of vector insert shifting. For each add_transition, we insert into a sorted vector. If the outdegree of a state becomes large (up to 62), insertion at the end or middle might shift up to 61 elements. So worst-case cost per insertion O(sigma). The total number of insertions is O(n). In worst-case, if many states have large outdegree, the total shifting could be O(n * sigma) which is 1e6 * 62 = 62e6, which is acceptable. But note that the outdegree of a state cannot exceed sigma (62). So maximum shift per insertion is at most 61. So total shifting operations is at most 61 * number of insertions, which is about 61 * (number of transitions). Number of transitions is O(n) ~ 2e6? Actually up to 3n = 3e6. So 3e6 * 61 ~ 183e6 element moves. Each move is a pair<char,int> (8 bytes). That's about 1.5 billion bytes moved, which might be significant but still plausible within time. However, it may be slower than map's O(log sigma) per operation because map's insertion involves dynamic allocation and tree balancing, which may be heavier. So vector may be competitive.
But we can further optimize by using a small fixed-size array for states with outdegree <= some threshold, but not needed.
Now we should also consider that we use lower_bound which requires random access iterators; it's fine.
Potential pitfalls: When we copy vector during clone, we do st[clone].next = st[q].next; This copies all transitions. That's O(outdegree(q)). Summed over all clones, total copying is O(total edges). That's fine.
Now consider the while loop in cloning where we update transitions: set_transition(p,c,clone). That uses binary search to find the transition and updates the target. That's O(log d).
Now after building SAM, for each query we traverse pattern: for each character, we call get_next which does binary search. That's O(|P| log sigma). With sum |P| up to 1e7, and log sigma ~6, total ~6e7 operations, fine.
Thus the solution should be efficient.
Now we should test with some random large input to ensure speed. But in reasoning, it should pass.
But there is nuance: When we add transitions, we assume that the vector is sorted and we use lower_bound to find insertion point. But after we insert, the vector remains sorted. However, note that we also have set_transition which modifies the target but does not change the key, so sorted order remains.
Now, could there be a case where we add transition to a state that already has a transition for that char? No, because we check with get_next before adding.
Now, one more nuance: In the while loop where we add transitions for p that lack transition, we may be adding the same character c to many states along the suffix links. That's typical.
Now memory: State vector's capacity may exceed 2n due to clones. We reserved 2n+5, but maximum states is 2*n-1, so it's fine.
Now we need to ensure we don't run out of memory due to vector growth: we reserved enough, so no reallocation.
Now we must include necessary headers: #include <bits/stdc++.h>
Now final code.
But wait: There's an issue: In get_next, we use make_pair(c, -1). But we compare pair<char,int> with pair<char,int>. Since char is first, lower_bound will compare pairs lexicographically. Using -1 for second is okay because we only care about first. However, if vector contains pairs with second possibly -1? That's unlikely. But it's fine.
Now consider if we use lower_bound with custom comparator to only compare first, but default comparator for pair compares both first and second. That works because we only care about first; using -1 for second might cause it to be less than some pair with same first but positive second, but lower_bound uses < operator. Since we use make_pair(c, -1), if there is an element (c, x) where x > -1, then (c, -1) < (c, x) because first equal and second -1 < x, so lower_bound will return the first element not less than (c, -1). Since (c, -1) < (c, x), lower_bound will return iterator to (c, x) if that is the first element with first >= c. But if there is an element (c, x), then (c, -1) < (c, x) so the lower_bound will point to that element (c, x). That's correct because we want to find element with first == c. So it works.
But if there is element with first > c, then (c, -1) < (d, ...) anyway.
So it's fine.
Now we must also consider that the pattern may be longer than any path in SAM, but we'll just fail when transition missing.
Now test with example:
T="aabaaa"
Build SAM manually? Not needed.
Now we need to ensure that we treat characters as char. That's fine.
Now potential optimization: Because we use vector for transitions, we can also store them sorted and use a small linear search for small vectors to avoid binary search overhead. But I think it's fine.
Now about reading patterns: Patterns may contain spaces? The problem says alphabetical characters and digits, so no spaces. So getline is fine.
Now time complexity: Building SAM: For each character of T, we do while loop that follows suffix links. In worst-case (string of same character), the number of times we go through while is O(n) amortized? Actually for repeated characters, each extend only causes one iteration? For "aaaa", the automaton is linear, and the while loop will travel many suffix links? Let's recall SAM construction: For repeated character, when adding a new 'a', we start at last, and while p != -1 and no transition for 'a', we add transition from p to cur. Since for all states except maybe the root, they already have transition for 'a'? Actually in a chain, each state already has an 'a' transition to the next state. So when we add new character, we start at last (state for "aaaa..."), then p = last, we check if has transition for 'a'? last might not have transition for 'a' because it's the newest state. So we add transition from last to cur? Actually last is the state representing whole current string. It has no outgoing edges yet. So we add transition from last to cur for 'a'. Then p = link[last] (which is previous state). That state may already have 'a' transition? In chain, each state (except maybe root) has an 'a' transition to the next state. So when we go to p = link[last], we check if it has transition for 'a'? It does, so while loop stops. So the number of iterations per extend is typically small. So overall O(n).
Now, in get_next we use binary search. The number of transitions per state is small, but binary search over a vector of size up to 62 is trivial.
Thus the algorithm should run quickly.
Now final code.
But we should also consider that we used vector<pair<char,int>> for transitions. However, we frequently call lower_bound, which uses operator< for pair. That's fine.
Now one more nuance: In the while loop of extend, we call get_next(p,c) to check existence. If not exist, we add_transition(p,c,cur). But after adding, we continue to p = st[p].link. That's correct.
Now for cloning, we copy the next vector. That copies all transitions. That might cause memory fragmentation because each vector stores its own dynamically allocated array. But total memory is as estimated.
Now we must ensure that we don't run into stack overflow; everything is on heap.
Now let's implement.
But wait: The while loop in extend uses get_next(p,c) which returns -1 if not found. But get_next uses lower_bound, which is O(log d). However, we also call get_next again inside the if after the while? Actually we call get_next(p,c) to get q after the loop. That's fine.
Now we must also be careful: In the while loop where we redirect transitions: while (p != -1 && get_next(p,c) == q). Here we need to check if the transition from p for c goes to q; if so, we change it to clone. This is standard.
Now one more nuance: When we set_transition(p,c,clone), we don't need to keep sorted order because we are only changing the target; the key remains same.
Now after cloning, we need to set st[q].link and st[cur].link to clone.
Now we must ensure that we do not cause iterator invalidation: when we add or set transitions, we are not iterating over vector while modifying it elsewhere; it's fine.
Now we should test with simple cases:
T = "a". Build SAM: states: 0 (root), 1 (for 'a').
extend('a'): cur=1, p=0; while: p=0, get_next(0,'a')? Initially no transition, so add_transition(0,'a',1). Then p = st[0].link = -1; exit while. p==-1 so link[1]=0. Done.
Query "a": start at 0, get_next(0,'a') = 1, so contains true.
Query "b": get_next(0,'b') = -1 false.
Works.
T = "ab". Build SAM manually? It's fine.
Now consider when we clone: e.g., T="abab". Should work.
Now we must also consider performance of binary search vs. map find. With vector, binary search might be faster due to cache. So okay.
Now potential bug: In add_transition, we call lower_bound, but after inserting, the vector may need to reallocate. For states with many transitions, the vector may need to grow. Since we don't know the final outdegree of each state beforehand, the vector will allocate and reallocate as we add transitions. This could cause some overhead but acceptable. However, if we add many transitions to the same state (like root), the vector may reallocate multiple times. But the maximum outdegree is at most 62, so at most a few reallocations. That's fine.
Now code is ready.
But we should also think about using array of size 128 for transitions for root only? Not needed.
Now we must handle input large: use getline for T, and for patterns. We must ensure we read Q correctly after T. Since T line may have trailing newline, we need to read Q. Using cin >> Q after getline for T? Actually after getline we have T, then we need to read Q. There's a newline after T that getline consumes (it reads up to newline). So T line ends with newline, getline reads T without newline. Then we can cin >> Q. But note that cin >> Q will read integer and leave the newline after integer. Then getline for patterns will read empty line if we don't skip that newline. So we need to ignore the newline after Q. We'll use cin.ignore() after reading Q.
But also patterns may be empty? The constraints say length >=1, so fine.
Now we need to output '1' or '0' for each query.
Now memory: We reserved 2e6+5 states. But what if T length is less? It's fine.
But we should compute max_states = 2 * T.size() maybe plus some. I'll compute: int max_states = 2 * T.size() + 5; then st.reserve(max_states).
Now let's think about potential bugs: In get_next, we use lower_bound, which requires that the vector is sorted. We ensure sorted insertion. But what about when we copy vector? The copy will preserve sorted order. Good.
But what about when we add_transition to a state that has not yet been sorted? We always insert using lower_bound to maintain sorted order. So it's fine.
Now verify that in the while loop of extend, we call add_transition(p,c,cur) only when we have checked that no transition exists. That's correct.
Now, in the clone part, we set_transition(p,c,clone). This updates an existing transition's target, but does not change the key, so sortedness remains.
Now, after cloning, we do not modify next[clone] later except for potential future extensions that may add transitions to clone via add_transition (which maintains sortedness).
Now one more: In the redirect while loop: while (p != -1 && get_next(p,c) == q) { set_transition(p,c,clone); p = st[p].link; }. This modifies transitions of p. But note that after we set_transition, the vector is still sorted (key unchanged). So fine.
Now we also need to consider that get_next uses binary search. In the redirect while, we call get_next(p,c) to check if it's q. That's fine.
Now we need to implement get_next efficiently: Since we may call get_next many times, we could store result of lower_bound, but not necessary.
Now let's test with example manually:
T = "aabaaa"
We'll simulate to ensure no error.
But I'm confident.
Now we should also consider that the SAM building algorithm as described works for all characters; we treat chars as is.
Now complexity wise, this should pass.
Edge Cases: T length 1,000,000 all distinct characters? For a string of all distinct characters (like increasing numbers?), the alphabet is only 62, so it cannot have more than 62 distinct characters. So distinct characters limited to 62. So not all distinct.
Now I'll finalize.
But there is another nuance: The input may contain uppercase and lowercase letters and digits. That's 62 characters. But are there any other characters like underscore? Not per problem.
Now final code.
But I realize: In get_next, we used lower_bound with make_pair(c, -1). However, the second element of the pair is int, and -1 is a valid int. But what if some transition's second element is -1? Not possible because state indices are non-negative (0,1,2,...). So -1 never appears as target. So fine.
Now we should also include #include for lower_bound, but <bits/stdc++.h> includes it.
Now compile and test.
I will write the code accordingly.
But there is a possible improvement: To reduce overhead of binary search for small vectors, we could implement a simple linear search if vec.size() is small (e.g., <=5). But