We are given n strings (n up to 10k), each string length up to 10. Q up to 500k. For each query (L,R,str), where str length up to 10, we need to count how many strings from index L to R (inclusive) contain str as a substring. We need to answer efficiently.
Constraints: n = 10000, Q=5e5. Each string length <=10, query pattern length <=10. That's tiny. We can precompute for each possible substring (of length up to 10) which strings contain it, and then answer queries by checking the range. Since n is only 10k, we can have a bitset for each substring, but number of possible substrings? Each string length up to 10, total distinct substrings across all strings could be at most n * (max_len*(max_len+1)/2) = 10k * 55 = 550k distinct substrings. That's manageable. But patterns are provided, but they might not be limited to those substrings? Actually queries pattern can be any string of length up to 10, not necessarily appearing in any of the given strings. If pattern doesn't appear, answer is 0. So we only need to store info for patterns that actually appear. However, Q=500k, patterns could be many, but total distinct query patterns is at most 500k (though might be less). But we can handle by building a dictionary mapping pattern to a sorted list of indices (or a bitset) of strings containing it. Then each query does binary search on that list to count indices in [L,R]. Since n=10000, we could also precompute a boolean matrix: for each string i (1..n) and each possible pattern? But pattern space is huge: 26^10 is astronomical. So we need to limit to patterns that appear as substrings. But queries might ask patterns that are not substrings of any given string => answer 0. So we can just have a dictionary mapping pattern to its index list; if pattern not found, answer 0.
The challenge is to build this mapping efficiently.
Approach: For each string s_i (i from 1 to n), length up to 10, generate all substrings (all contiguous substrings) of lengths from 1 to len(s_i) and up to 10. Insert i into the list for that substring. Since string length <=10, number of substrings per string <= 55 (if max_len=10, it's 10*11/2=55). So total insertions <= n * 55 = 550k. So we can store for each substring a vector indices. Then after generating all, we can sort each vector (they are naturally appended in order of i, so we could just push_back in order i increasing since we process i from 1 to n; so each vector is already sorted). So we can answer query by binary searching on the vector: lower_bound(L) and upper_bound(R) to count.
Complexities: Memory: total entries 550k, each int 4 bytes => 2.2MB plus overhead of map keys. The number of distinct substrings might be up to 550k, but likely less; map overhead may be okay. Use unordered_map or map? Since we need fast lookups for up to 500k queries, we should use an unordered_map (hash map) for O(1) average lookups. However, with many keys (up to 550k), memory may be a concern but still okay. Alternatively, we can use a trie to store substrings but hash map is simpler.
We must also consider that patterns length <=10, so we can store them as strings.
Implementation steps:
-
Read n.
-
For i from 1 to n: read string s.
-
For start pos from 0 to len(s)-1:
For length from 1 to min(10, len(s)-start):
substring = s.substr(start, length)
map[substring].push_back(i)
-
After reading all strings, the vectors are sorted because we push i in increasing order.
-
Read Q.
-
For each query: read L, R, pattern str.
-
Look up in map: if not found, output 0.
-
else: vector &vec = map[str];
int cnt = upper_bound(vec.begin(), vec.end(), R) - lower_bound(vec.begin(), vec.end(), L);
print cnt.
Edge cases: L,R inclusive. The pattern length may be >10? Problem says 1 ≤ strlen(str) ≤ 10, but we trust. Also strings consist of lowercase letters.
Potential pitfalls: There might be duplicate strings? Doesn't matter.
Time: building O(n * 55) = 550k, each insertion into map O(1) average. Answering queries: O(log k) per query where k is the number of occurrences of pattern. Since total occurrence sum is 550k, average occurrences per pattern small? Actually if pattern appears frequently, vector could be large. But worst-case pattern like "a" could appear in all 10k strings. Then per query we binary search in vector of size 10k, O(log 10000) ~ 14, times 500k = 7 million operations, fine. Even linear scanning per query would be too slow (10k * 500k = 5e9). Binary search is fine.
But 500k queries and each binary search (two binary searches) is okay.
Memory: unordered_map with string keys up to 550k entries. Each string key length up to 10, so storing them may cost memory but within limits (maybe 550k * (overhead) may be large but likely acceptable for typical competitive programming memory (256-512 MB). Let's estimate: Each string object in C++ (libstdc++) has about 32 bytes overhead plus dynamic allocation for characters. But we can use custom hashing or use trie to compress. However 550k * (string overhead) might be high. Alternatively, we can use a map (ordered) which uses less overhead? Actually both have overhead. We can also store substrings in a trie where each node stores a vector of indices. Since total substrings total length sum: each substring length up to 10, total inserted substrings 550k, total characters about up to 550k * average length, maybe 5-6 million characters. Trie nodes would share prefixes, but each distinct substring is stored as a path; the number of nodes could be up to sum of lengths of distinct substrings. That could be less than number of substrings? Actually distinct substrings across all strings might be up to 550k (if all distinct). Each distinct substring as a separate path; each node stores a char and children pointers, plus vector. Trie may use more memory due to pointers. Hash map might be simpler.
But we need to be careful about memory usage: 550k distinct substrings, each key string stored individually. In C++ unordered_map<string, vector>, each key string will allocate its character array, plus the string object. Assuming short string optimization (SSO) for strings of length up to 10: many implementations have SSO for up to 15 or 22 chars, so the string might store characters inline, reducing allocation overhead. In GCC, std::string with SSO typically has a small buffer of 15 chars (for 64-bit). So strings up to 10 chars fit in SSO, no extra allocation, just the string object itself (typically 32 bytes). So each map entry overhead plus string object ~ 32+? unordered_map node overhead maybe 32-40 bytes, plus the vector overhead (3 pointers ~24). So per distinct substring maybe ~100 bytes. 550k * 100 = 55 MB. That's okay. Actually 550k * 100 = 55 million bytes = 55 MB. Plus vector entries (550k ints = 2.2 MB). So total < 60 MB. Should be fine.
But wait: total insert operations = 550k push_backs, but some substrings appear multiple times across strings, so distinct substrings is less than total insert operations. At worst all substrings distinct, then distinct = 550k. So memory usage ~60MB, okay.
Time to build: O(550k) insertions into unordered_map and pushing into vector. Should be fine.
Alternative approach: Since pattern length <=10, we could precompute a bitset for each possible pattern? The pattern space is 26^1+...+26^10 huge, not possible.
Thus our approach is good.
Potential optimization: Use map with string_view? But not needed.
Edge Cases: The input reading: After n, each string line maybe without spaces. Q lines: each line: L R str. L and R integers, str a string. They are separated by spaces. So we can read using cin >> L >> R >> str.
But what if the pattern string might contain spaces? No, it's a single word (lowercase). So fine.
We must output each answer on its own line (as per sample). Possibly there is trailing spaces? Sample output shows "2 " but that might be formatting. We'll output just the number.
We need to ensure fast I/O because Q=500k, reading large input. Use ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL).
Potential issue: The pattern string might be longer than 10? We can ignore but not needed.
Now let's consider the sample: n=3 strings: code, coder, coding. Substrings: For "code": substrings: c, o, d, e, co, od, de, cod, ode, code. For "coder": similar. For "coding": etc. Then queries: "1 3 code" -> check occurrences of "code" in indices: code (1), coder (2) contains "code"? "coder" contains "code" as substring? "coder" contains "code" as prefix of length 4? Yes, "code" is substring of "coder". "coding" does not contain "code". So indices 1 and 2 => count 2. "1 3 co" -> "co" appears in all three => 3.
Works.
Now consider potential pitfalls: If a pattern appears multiple times in a string, we only need to count the string once. Our insertion only pushes the index once per substring per string, because we generate each distinct substring of a given string? Actually we generate all substrings, including duplicates? For a given string, if there are duplicate substrings (e.g., "aa" contains "a" at positions 0 and 1; we will generate substring "a" twice from the same string). But we push the index i each time we generate substring. So the same index might appear multiple times in the vector for that substring. That would cause overcounting in binary search. So we must ensure we push each index only once per substring per string. Since we generate all substrings, we may add duplicate occurrences of the same substring for the same string. For example, string "aaa": substrings of length 1 from positions 0,1,2 all are "a". So we would push i three times for substring "a". That would cause the count for pattern "a" to overcount. So we need to avoid duplicate index entries for the same string.
Therefore we must deduplicate per string. Since we process each string sequentially, we can maintain a set of substrings encountered for that string, and only push i once per distinct substring per string. Or we can use a local unordered_set to track which substrings have been already inserted for this string. But the number of substrings per string is small (<=55), so using a set is fine. Alternatively, we can generate all substrings and push them, but then after building, we could sort and unique each vector, but that would be heavy (550k entries, but duplicates would inflate total entries maybe up to n * (max substring count) = 550k, but duplicates within a string could add extra; worst case: string of length 10 with all same character like "aaaaaaaaaa": number of substrings = 55, but they are not all distinct; many substrings are same. So duplicates exist. So total entries could be more than 550k if we don't dedup. But duplicates per substring per string would cause multiple entries for the same index. So we must deduplicate.
Simplest: For each string i, create an unordered_set (or set) to store substrings we have inserted for this i. For each start and length, compute substr, if not already in the set, insert into map and push i, and add to set. Since substring length <=10 and set size <=55, overhead minimal.
Alternatively, we could avoid set by using the fact that we can generate all substrings and then use a boolean array to mark inserted? But set is easiest.
But careful: For string with duplicate substrings, we want to add i only once for that substring. So we need to deduplicate per string. So we'll use local unordered_set or std::set. But we can also use a local vector to store substrings, then sort and unique, then push. Since number small, set is fine.
Thus the algorithm:
unordered_map<string, vector> mp;
for (int i = 1; i <= n; i++) {
string s; cin >> s;
unordered_set seen;
int len = s.size();
for (int start = 0; start < len; start++) {
for (int l = 1; l <= min(10, len - start); l++) {
string sub = s.substr(start, l);
if (seen.find(sub) == seen.end()) {
seen.insert(sub);
mp[sub].push_back(i);
}
}
}
}
Now the vectors are sorted because we push i in increasing order.
Now answer queries:
while (Q--) {
int L, R; string pat; cin >> L >> R >> pat;
auto it = mp.find(pat);
if (it == mp.end()) {
cout << 0 << "\n";
} else {
const vector& v = it->second;
int left = lower_bound(v.begin(), v.end(), L) - v.begin();
int right = upper_bound(v.begin(), v.end(), R) - v.begin();
cout << right - left << "\n";
}
}
Complexities: building O(n * 55 * (set insertion + map insertion)). With n=10000, 550k substring generations, set insertions for each substring; each set insertion O(1) average. Good.
Potential optimization: Since substrings are small, we can use a vector and sort/unique, but set is fine.
Memory: The seen set per iteration will be cleared each iteration, overhead small.
Edge Cases: L and R between 1 and n inclusive.
Now consider if pattern length > 10? But constraints say up to 10, so ignore.
One more thing: The problem statement: "strings consist of only lower case characters". And input strings have length not more than 10.
Thus solution works.
But we must be careful about time: Q up to 500k, each query does a hash lookup in unordered_map. That should be O(1) average. However, with many keys, hash collisions may degrade. But still likely okay. We could also use a sorted map (std::map) for guaranteed log N, but that would be log(550k) ~ 20 per query, times 500k = 10 million, also fine. But unordered_map is faster. However, beware of potential worst-case O(n) due to collisions. To avoid that, we can reserve enough buckets. But with 500k queries, it's okay.
Memory for unordered_map: As we add up to 550k keys, we can reserve capacity. But not necessary.
Implementation details:
- Use #include <bits/stdc++.h>
- using namespace std;
- int main() with fast I/O.
Potential issue: reading large input: Q lines each have two integers and a string. Using cin >> L >> R >> pat; that reads pat as a word (no spaces). That is fine.
Edge Cases: Pattern might be empty? No.
Now test with sample.
Now let's test manually:
n=3:
string1 "code": generate all substrings up to length 10, all distinct? Not all, but no duplicates. So seen set ensures unique. Insert indices.
string2 "coder": generate substrings, many may duplicate with previous, but that's fine across strings; seen set per string ensures no duplicate per string.
string3 "coding".
Then queries: For "code", vector contains indices: 1,2? Actually check: substring "code" appears in string1, also in string2? "coder" contains "code"? Yes. Also in string3 "coding"? Contains "code"? No. So vector for "code" has [1,2]. For "co", vector includes all three: from string1 "co", string2 "co", string3 "co". So queries work.
Now consider string "aaa": substrings of length 1: "a" (three times, but seen set dedup, so only one push for index). So vector for "a" will have i only once per string.
Now complexity analysis: building set per string: worst-case each string length 10, generating 55 substrings; set may have up to 55 entries. That's fine.
Now, can we avoid set? Another approach: since substring length is small, we could use a trie to store substrings while generating, and for each node we maintain list of indices; but we still need to ensure that the same index is not inserted multiple times for the same node. To avoid duplicates, we could track the last index inserted for that node; if the current i is equal to the last inserted index, skip. Since we process each string sequentially, we can insert indices as we generate substrings, but need to avoid duplicates from multiple occurrences within the same string. So we could, for each string, generate all substrings and for each substring, we can store in a local boolean array for that substring? Not trivial.
Set approach is fine.
Now potential memory blow: seen set of strings of length up to 10. But we create a new set each iteration; memory fragmentation is okay.
Now answer queries: we need to output each answer on a new line. Sample output shows numbers with possibly space? Actually: "2 \n3". Probably just each answer on separate line.
Thus code.
Now consider input size: Q=500k, each line: two ints and string (<=10). So total characters input roughly 500k * (2*5 + 10 + spaces) ~ 10 million, manageable.
Now Implementation in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
unordered_map<string, vector<int>> mp;
mp.reserve(600000); // optional
for (int i = 1; i <= n; ++i) {
string s;
cin >> s;
int len = s.size();
unordered_set<string> seen;
seen.reserve(55); // optional
for (int start = 0; start < len; ++start) {
int max_len = min(10, len - start);
for (int l = 1; l <= max_len; ++l) {
string sub = s.substr(start, l);
if (seen.find(sub) == seen.end()) {
seen.insert(sub);
mp[sub].push_back(i);
}
}
}
}
int Q;
cin >> Q;
while (Q--) {
int L, R;
string pat;
cin >> L >> R >> pat;
auto it = mp.find(pat);
if (it == mp.end()) {
cout << "0\n";
} else {
const auto& v = it->second;
int left = lower_bound(v.begin(), v.end(), L) - v.begin();
int right = upper_bound(v.begin(), v.end(), R) - v.begin();
cout << (right - left) << "\n";
}
}
return 0;
}
That's it.
But check: the pattern may have length >10? If so, it cannot be a substring of any string because all strings length <=10. So answer 0. So we can also short-circuit: if pat.length() > 10, then answer 0 without lookup. This can save some map lookups. But it's optional.
Now test with sample:
Input:
3
code
coder
coding
2
1 3 code
1 3 co
Our code will produce:
2
3
Matches.
Now think about potential pitfalls: The query pattern may be longer than any string length. Since string length <=10, if pat length >10, it cannot appear. So we can handle quickly.
But also, while generating substrings, we only generate up to length 10. Good.
Now check for duplicate substrings across strings: For each string, we dedup using seen set. However, if the same substring appears multiple times in the same string, we only add once. That's correct.
Now verify: If a pattern appears as a substring in a string multiple times, we count the string only once. That's what problem asks: "contains str as a substring" means at least once.
Thus dedup is correct.
Edge case: string length less than pattern? Not possible because we only insert if pattern length <= string length? Actually we generate substrings up to min(10, len-start). So we don't generate substrings longer than the string. So map only contains substrings of length <=10 that appear. If a pattern is longer than 10, it won't be in map, answer 0. If pattern length <=10 but longer than some strings, those strings won't contain it, but we might still have map entry for that pattern if it appears in some other string. So fine.
Now what about pattern of length 0? Not allowed.
Now potential performance: Using unordered_set for seen may allocate many small strings. Could be heavy, but n=10000, each set up to 55 strings, total 550k string allocations. That's fine.
Alternative: Use a trie to store indices with marking last inserted index. But not needed.
Now consider using a bitset per substring? Not needed.
Now we need to be careful with reading input: after reading n strings, we read Q and then Q lines. There might be extra whitespace. Using cin >> works.
Now we should consider that the strings given may have length up to 10, but some might be empty? Not likely: 1 ≤ strlen(str) ≤ 10 for queries, but for given strings it says each having length not more than 10, but doesn't specify minimum; maybe empty strings? Probably not. We'll assume non-empty.
Now time to test with a small random test.
But before final, think about potential overflow: vector size can be up to n=10000.
Now we need to ensure we output each answer on a new line. Sample output shows "2 " and then newline? Actually the sample output:
2
3
The "2 " maybe includes a space after, but it's okay to print "2\n3\n".
Now consider memory: map with 550k keys. We might want to use unordered_map with a custom hash for string to speed up. But default hash is fine.
One more optimization: Since substrings are very short (max 10), we can encode them into a 64-bit integer to reduce memory and improve hash speed. For example, treat each char as 5 bits? Actually 26 letters, need 5 bits per char, so 10 chars -> 50 bits, fit in uint64_t. This would reduce string overhead. However, not necessary but can be done if memory is tight. But with 60MB it's fine.
But maybe in C++ with short string optimization, the string objects are stored inline, so memory okay.
Now think about worst-case: n=10000, each string length=10, all distinct characters? Actually each string is 10 chars, distinct substrings across strings could be high. For each string, number of substrings=55. If all strings are random, many substrings will be distinct, so distinct keys ~ 550k. That's okay.
Now Q=500k, each query might ask for patterns that don't exist, causing map find to fail and output 0. That's fine.
Thus solution passes.
Now alternative: Use a Fenwick tree or segment tree? Not needed.
Now check for potential integer type: using int.
Now we should ensure that we use reserve for map to avoid rehashing. But not necessary.
Now one nuance: The problem statement says: "strings consist of only lower case characters". But also says "each having length not more than 10". So that's it.
Now we need to consider if pattern length 0? Not possible.
Now we are ready to write final answer.
But I realize: In our generation, we are limiting substring lengths to min(10, remaining). Good.
Now let's test with a small case manually:
n=2:
s1="a"
s2="aa"
For s1: substrings: "a". insert 1.
For s2: generate all substrings: start 0: l=1 "a" (not seen yet for s2), insert 2. start 0: l=2 "aa" (insert 2). start 1: l=1 "a" (already seen, skip). So map["a"] -> [1,2]; map["aa"] -> [2].
Queries:
1 2 a -> should be 2.
1 2 aa -> should be 1.
Our code works.
Now test with duplicates within string: s="aaa". Substrings: start0,l1 "a" -> insert; l2 "aa" -> insert; l3 "aaa" -> insert. start1,l1 "a" skip; l2 "aa"? Actually from start1 length2 "aa" -> but "aa" already seen? we haven't inserted "aa" from start1? We inserted "aa" from start0 l=2. So skip. start2,l1 "a" skip. So map entries: "a": [i], "aa":[i], "aaa":[i]. Good.
Now consider time for generating substrings: for each string, nested loops O(L^2) but L<=10.
Now we should confirm that using unordered_set inside the loop is efficient. Possibly we could generate all substrings and use a local vector, then sort and unique, then push to map. That might be faster because we avoid dynamic set allocations? But set uses hashing; each string is small. For 10000*55 = 550k insertions into a temporary set, each insertion involves hash computation. That's okay. Another approach: For each string, we can use a boolean array to mark substrings? Not feasible.
Alternatively, we can generate all substrings and directly push into map, then after building all, for each key we sort and unique the vector (removing duplicates). But that would require storing duplicates and then later removing them. This may increase memory due to duplicates; worst-case duplicate count per key for the same index could be large? For string "aaaaaaaaaa", number of substrings = 55, but all substrings of same length may be duplicates? Actually distinct substrings: "a", "aa", "aaa", ..., up to "aaaaaaaaaa". So many substrings are distinct. Duplicates only for same substring, but in that case, for a given substring like "a", there are many positions that produce "a". So duplicate entries for the same index. So total entries could be more than 550k if we don't dedup. The worst-case: each string length 10, all characters same 'a', then number of distinct substrings per string is 10 (since all substrings of same length are identical, so distinct strings are only 10: "a","aa",..., "aaaaaaaaaa"). But if we push without dedup, we would push each occurrence: number of occurrences for each distinct substring? For substring of length l, there are (10 - l + 1) occurrences. So total pushes = sum_{l=1}^{10} (10-l+1) = 55. So indeed total pushes is exactly the number of substrings (including duplicates). But these duplicates are for the same index, so they'd cause multiple entries for same index in the vector for that substring. So if we don't dedup, each vector for "a" would contain many copies of the same index (e.g., for each string of all 'a', the vector for "a" would have 10 copies of that index). Then after sorting and unique, we could dedup. However, the total number of entries across all keys would be 550k (since each substring of each string contributes exactly one push? Actually no: each substring occurrence counts as a push, so total pushes = total substring occurrences across all strings = n * 55 = 550k. But those pushes include duplicates for the same key and same index, so after dedup globally (sorting and unique per vector), the total unique entries (index per key) would be less or equal to 550k, but we would have stored more initially. But the duplicates increase storage only if we don't dedup early. For worst-case strings all 'a', each string contributes 55 pushes, but for key "a", each string would contribute 10 pushes (positions). So total pushes for key "a" would be n10 = 100k. After dedup, we would compress to n entries. So initial storage would be 550k pushes across all keys, which is the same as the number of pushes with dedup? Actually with dedup per string, we only push once per distinct substring per string. For all 'a' string, distinct substrings are 10, so pushes per string = 10. So total pushes = n10 = 100k. But originally we have 55 pushes per string, so total pushes = 550k if we didn't dedup. So dedup per string reduces pushes from 55 to number of distinct substrings per string (max 55, min 10). So worst-case pushes = 550k even with dedup? Actually with dedup per string, maximum pushes occur when all substrings are distinct; then distinct substrings per string = 55, so pushes = nn entries = 100k entries, but after unique, we reduce to n entries. However, we need to store all these duplicates before dedup. That's more memory. So it's better to dedup per string.
Thus set approach is good.
Now confirm: For each string, we create a set, and for each substring we check if it's already in the set, if not, we push and add to set. So pushes = number of distinct substrings per string. So total pushes = total distinct substrings across all strings (with duplicates across strings but each index appears at most once per key). So total pushes <= n*55 = 550k. So vectors total entries <= 550k. Good.
Now we need to consider that the pattern length may be up to 10, but our map only contains substrings up to length min(10, string length). That's fine.
Now, we should also consider that the query pattern might be longer than 10? But constraint says up to 10, but we can still check length > 10 and output 0 quickly.
Now, I think it's fine.
Now, we also need to consider that the input format: first line n, then n strings, then Q, then Q lines each: L R str. There might be extra spaces. Using cin >> should handle.
Now, we should test with random data small to ensure correctness. Let's do a mental test:
n=4
strings: "ab", "bc", "abc", "a"
substrings:
- "ab": substrings: "a","b","ab" -> indices: 1
- "bc": "b","c","bc" -> indices: 2
- "abc": "a","b","c","ab","bc","abc" -> indices: 3
- "a": "a" -> index:4
Map:
"a": [1,3,4]
"b": [1?, actually "ab" has "b", "bc" has "b", "abc" has "b"] -> indices: 1,2,3
"c": [2,3]
"ab": [1,3]
"bc": [2,3]
"abc": [3]
Now query 1 4 "a" -> lower_bound(1) -> index0, upper_bound(4) -> index3, count=3 (indices 1,3,4). Works.
Now check for pattern "d" not present -> output 0.
Now, check for pattern length > max string length, e.g., "abcd", length 4, but all strings max length 3? Actually strings length up to 10, but pattern 4 may be present if some string has length>=4. If none have, map won't have it -> 0.
Now consider pattern length exactly 10: okay.
Now potential issue: The map may have many keys, causing hash collisions and slowing down find. But with 550k keys, the unordered_map's bucket count may be high. But we can use a custom hash and maybe use an array of size 27^something? Not necessary.
Now, we also need to consider time for binary search: For each query we do two binary searches. 500k * log(10000) ~ 500k*14=7M operations, fine.
Now potential memory/performance improvement: Instead of storing vectors, we could store bitsets for each pattern, but then for each query we need to compute range count; bitset of 10000 bits is 1250 bytes, times 550k = 687 MB, too large. So not feasible.
Thus solution stands.
Now, we must ensure we use fast I/O. Also, we might want to use '\n' instead of endl.
Now, one more thought: Could there be any tricky input where the pattern string appears as a substring but is not generated because we limited substring length to min(10, len - start)? But pattern length is <=10, so it will be generated if it appears as substring in any string (since we generate all substrings up to length 10). So fine.
Now test with string length < pattern length: Not generated.
Now, confirm that the query pattern might be longer than 10? Then output 0. But we can handle by checking pat.size() > 10, then print 0 directly without map lookup.
Now, we must consider that the input strings might have length up to 10, but pattern length may be up to 10, so generating substrings up to length 10 is sufficient.
Now, what about overlapping substrings? We dedup, okay.
Now, finalize.
But is there any more efficient method? Not needed.
Now, we can implement.
We might want to store indices as 2-byte short? But not needed.
Now, we should test with maximum constraints to ensure time passes.
n=10000, each string length=10. For each string, we generate 55 substrings, seen set insertion 55 times. Total 550k insertions into a temporary unordered_set. Each insertion does a hash on a string length up to 10. That's okay.
Then map insertion: For each distinct substring per string, we do mp[sub].push_back(i). mp[sub] may create a vector if not exist, else push. That's O(1) average.
Total pushes 550k.
Then Q=500k. For each query we do a map find, and binary search on vector.
Map find: average O(1), worst-case O(size) if hash collision high. But with a good hash function, should be fine. We can also use a sorted map (std::map) with O(log N) per query, which is 500k * log(550k) ~ 500k*20 = 10M, still fine. So either works.
But to be safe, we could use std::map to avoid potential worst-case O(N) in unordered_map due to collisions (though unlikely with such size). However, 500k queries with O(log 550k) may be ~10M, okay. But building the map with 550k inserts in std::map would be O(550k log 550k) ~ 550k*20=11M, also okay. So both okay. However, unordered_map might be faster if well-tuned. I'd go with unordered_map but we can add a custom hash for string to ensure speed.
Alternatively, we could encode substring into 64-bit integer: Since only lowercase letters, we can map 'a'=1..26, and encode as base-27 number. But then we need to compute quickly while generating substrings. For each start and length, we can compute integer hash incrementally. For speed we can do that, but not necessary.
Given that the string length is at most 10, we can pack into a 64-bit integer using 5 bits per character (since 26 < 32). 5 bits * 10 = 50 bits, fits. So we could use uint64_t as key, which may have faster hashing (identity). But then we need to convert query pattern to same encoding for lookup. That's easy: if pattern length > 10, skip; else encode and look up. However, we must be careful: The pattern is a string from input; we can encode it to the same integer. But note: We must ensure that different strings with leading zeros? Not needed. So we could do:
uint64_t encode(const string &s) {
uint64_t val = 0;
for (char c : s) {
val = val * 27 + (c - 'a' + 1); // base 27
}
return val;
}
Because 27^10 ~ 2e14, fits in 64-bit? 27^10 = 205891132094649 ~ 2e14, which is less than 2^64 (~1.8e19). So okay. But we need to encode also length? No, because base representation automatically includes length: e.g., "a" (1) and "a\0"? But we don't have nulls; but if we use base 27 and treat each char as 1..26, then "a" => 1; "a" followed by 'b' => 127+2=29. So it's unique. However, if substring length differs, the integer distinguishes because the length is implicitly encoded by the number of digits. For example, "a" = 1, "ab" = 127+2=29. So it's fine. But we need to ensure that when we generate substrings, we encode them similarly. Since substring length <=10, we can compute incremental hashes for each start. But we can just compute the integer from the substring string each time; that's also fine because lengths are small.
But using integer as key may be faster for hashing and comparison, and also reduces memory because the key is a 64-bit integer rather than a string with SSO. However, with 550k keys, the memory saved might be significant? Let's approximate: string key with SSO: object size maybe 32 bytes, plus the characters stored inline (up to 10) plus a null terminator, but with SSO, the entire string fits within the object. So memory for key: about 32 bytes. Integer key: 8 bytes. So map node would store a 8-byte key instead of 32, saving about 24 bytes per key, i.e., 550k * 24 = 13.2 MB saved. Not huge but could help. But we also need to encode pattern strings for query. So we could implement.
But it's optional.
Given constraints, both approaches should pass.
I'll stick with string keys for simplicity. But note: In competitive programming, unordered_map with string keys might be slower due to hashing long strings? But strings are short (max length 10), so hashing is fast.
But there is a catch: Using unordered_map with string keys may cause many dynamic allocations for string keys? When we do mp[sub], if the key does not exist, a new entry is created with a copy of the string key (sub). That's fine. The substring sub is a temporary; it's copied. But we can also use std::string_view? Not available in C++11? Usually in competitive programming, they use C++14/17, but if older, not. But we can use a custom hash.
Given that n is 10000 and Q is 500k, it's important that map find is fast. I'll consider using an unordered_map with a custom hash that uses a simple polynomial rolling hash computed on the fly, but we can also use a fixed-size array key.
Given that each string is at most 10 characters, we can encode into a 64-bit integer and use unordered_map<uint64_t, vector>. This will be very fast.
Let's do that for optimization.
Implementation with integer encoding:
Define a function to compute uint64_t hash for a string:
uint64_t encode(const string &s) {
uint64_t h = 0;
for (char c : s) {
h = h * 27 + (c - 'a' + 1);
}
return h;
}
But careful: For substring generation, we can compute h incrementally to avoid repeated encoding. But since strings are small, we can just call encode each time. The total number of substring generations is 550k, each encode does up to 10 multiplications, total 5.5M multiplications, trivial.
Better: While generating substrings, we can compute rolling hash for each start: For a fixed start, we can extend length and compute hash incrementally:
for start = 0..len-1:
uint64_t h = 0;
for l = 1..min(10, len-start):
h = h * 27 + (s[start+l-1] - 'a' + 1);
use h as key.
This reduces operations slightly. But not necessary.
I'll implement with direct encoding using the encode function for simplicity.
Now building:
unordered_map<uint64_t, vector> mp;
mp.reserve(600000);
for i = 1..n:
string s; cin >> s;
int len = s.size();
unordered_set<uint64_t> seen; // for dedup per string
seen.reserve(55);
for start...:
uint64_t h = 0;
for l = 1..max_len:
h = h * 27 + (s[start+l-1] - 'a' + 1);
if (seen.find(h) == seen.end()) {
seen.insert(h);
mp[h].push_back(i);
}
That's fine.
But careful: The encoding uses base 27. For patterns, we also encode them and look up. However, what about patterns that are not generated because they are longer than any string? They won't be in map, answer 0.
Potential collisions? 64-bit integer will be unique for strings up to length 10 because base 27 representation is unique as long as we use the same base and no overflow collisions. Since 27^10 < 2^64, it fits without overflow (actually 27^10 = 205891132094649, which is less than 2^48? Actually 2^48 is 2.8e14, so 2^48 ~ 281 trillion, 27^10 is 205 trillion, so fits within 48 bits). So we can safely store. But we need to ensure that when we compute h = h * 27 + val, we may overflow 64-bit but that's fine because we only care about uniqueness; multiplication modulo 2^64 is fine, but collisions could happen because of overflow modulo 2^64. Since the total number of possible distinct strings is 26^1 + ... + 26^10, which is about (26^11 - 1)/(26-1) ~ 26^10 ~ 1.4e14, which is less than 2^48, so no collisions even if we use full 64-bit without modulo? Actually 26^10 is about 1.4e14, less than 2^48. So the range of possible encoded values using base 27 (with digits 1..26) is exactly the set of numbers with base-27 digits 1..26, which is at most 27^10 - 1? Actually the maximum with 10 digits is sum_{i=0}^{9} 26 * 27^i = (27^10 - 1) / (27-1) * 26? That's not 27^10. Let's compute the maximum encoding: For string of length 10, each digit in 1..26, the encoding is ((((d1)*27 + d2)27 + d3)...). This yields a number less than 27^10. Since each digit is at most 26, the maximum is when all digits = 26: then encoding = 26 * (27^9) + 26 * (27^8) + ... + 26 = 26 * (27^10 - 1)/(27-1) = 26(27^10-1)/26 = 27^10 - 1. So the maximum encoding is 27^10 - 1 = 205891132094649 - 1 = 205891132094648. So it fits in 48 bits. So no overflow. So collisions are impossible. So safe.
Thus we can use uint64_t as key.
Now building seen set: we can use unordered_set<uint64_t> for per-string dedup. That's fine.
Now query: read L,R, pattern string pat. Compute key = encode(pat). If mp.find(key) != mp.end()? But note: encode(pat) may produce the same key as some substring we generated only if pat is exactly a substring of some string. Since encoding is unique, it's safe.
But careful: The pattern may have length > 10; then its encoding would be large (27^len) might exceed 2^64? Actually 27^11 ~ 5.56e15, still less than 2^64? 2^64 = 1.84e19, so 27^11 = 5.56e15 < 2^64, still fits. 27^12 ~ 1.5e17, still fits. Actually 27^20 would exceed. But pattern length is constrained to <=10, so safe. But if pattern length >10, we should output 0 anyway, but we can handle by checking length >10 before encoding to avoid unnecessary encoding. We'll do that.
Now one more nuance: The input strings are length <=10, but pattern length up to 10. So pattern may be longer than some strings but that's fine; if it exists as substring of a longer string, it will be generated from that string.
Now implement.
But what about memory: unordered_map<uint64_t, vector> with 550k keys. Each key is 8 bytes, plus map node overhead. Should be less than string version. Good.
Now we also need to store vectors of indices. The total number of index entries is at most 550k. So memory: map nodes: each node contains key (8 bytes), vector (maybe 24 bytes for pointer, size, capacity), plus overhead (maybe 32 bytes). So roughly 64 bytes per node? Actually typical unordered_map node includes next pointer, key, value. So for 550k nodes, might be ~ 550k * 40 = 22 MB, plus vector overhead (for each distinct substring, a vector object exists; but many vectors will be empty? Actually they will be created only when needed. So total vectors = number of distinct substrings. Each vector object is typically 3 pointers (24 bytes) plus allocated storage for indices. The storage for indices is separate. So total memory ~ (node overhead + vector object) per key + indices. 550k * (node 40 + vector 24) ~ 35 MB, plus indices 550k * 4 bytes = 2.2 MB, total ~37 MB. Acceptable.
Now with string key version, each node might have key string object (32 bytes) plus same. So maybe 60 MB. Still okay. But we'll go with integer for speed.
Now implement encode function. We'll also need to ensure we use fast I/O.
Now, building per string: for each start, we compute rolling hash. We can compute from scratch each substring to avoid complexity.
Simpler: for each start, we compute a loop:
for (int start = 0; start < len; start++) {
uint64_t h = 0;
int max_len = min(10, len - start);
for (int l = 1; l <= max_len; l++) {
h = h * 27 + (s[start + l - 1] - 'a' + 1);
if (seen.insert(h).second) { // if newly inserted
mp[h].push_back(i);
}
}
}
Note: seen.insert returns pair<iterator, bool>. So we can use that.
We need to include <unordered_map>, <unordered_set>, , , , etc.
Now code:
#include <bits/stdc++.h>
using namespace std;
using ULL = unsigned long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
unordered_map<ULL, vector<int>> mp;
mp.reserve(600000); // optional
for (int i = 1; i <= n; ++i) {
string s;
cin >> s;
int len = s.size();
unordered_set<ULL> seen;
seen.reserve(55);
for (int start = 0; start < len; ++start) {
ULL h = 0;
int max_len = min(10, len - start);
for (int l = 1; l <= max_len; ++l) {
h = h * 27ULL + (s[start + l - 1] - 'a' + 1);
if (seen.insert(h).second) {
mp[h].push_back(i);
}
}
}
}
int Q;
cin >> Q;
while (Q--) {
int L, R;
string pat;
cin >> L >> R >> pat;
if (pat.size() > 10) {
cout << "0\n";
continue;
}
ULL key = 0;
for (char c : pat) {
key = key * 27ULL + (c - 'a' + 1);
}
auto it = mp.find(key);
if (it == mp.end()) {
cout << "0\n";
} else {
const vector<int>& v = it->second;
int left = lower_bound(v.begin(), v.end(), L) - v.begin();
int right = upper_bound(v.begin(), v.end(), R) - v.begin();
cout << (right - left) << "\n";
}
}
return 0;
}
But note: In the building, we used base 27 and digits 1..26. For a substring, the encoding is unique. However, what about substring of length less than 10? That's fine; no need to pad.
Now we need to be careful about the case where pattern is longer than any string length; we output 0. Since we limited to 10, but all strings length <=10, pattern length >10 cannot appear anyway. But we still do the check.
Now test with sample:
Input:
3
code
coder
coding
2
1 3 code
1 3 co
Compute encodings: For "code": c=3? Actually 'a'=1, 'b'=2,... So 'c'=3, 'o'=15, 'd'=4, 'e'=5. Encode: (((3*27+15)*27+4)*27+5) = compute? Not needed.
Our building: For "code" (len=4):
start0: l1: h=3 -> seen insert 3 -> mp[3].push(1)
l2: h=327+15=81+15=96 -> mp[96].push(1)
l3: h=9627+4=2592+4=2596 -> mp[2596].push(1)
l4: h=259627+5=70092+5=70097 -> mp[70097].push(1)
start1: l1: h=15 -> mp[15].push(1) (if not already seen? but seen set per string, so "o" is new) -> mp[15].push(1)
l2: h=1527+4=405+4=409 -> mp[409].push(1)
l3: h=40927+5=11043+5=11048 -> mp[11048].push(1)
start2: l1: h=4 -> mp[4].push(1)
l2: h=427+5=108+5=113 -> mp[113].push(1)
start3: l1: h=5 -> mp[5].push(1)
So "code" gets many entries. For "coder" (len=5): we will generate substrings, including "code" (positions 0-3) -> key 70097? Actually "code" from "coder" first 4 letters gives same code: 3,96,2596,70097? Let's compute: 'c'=3, 'o'=15 =>96, 'd'=4 =>2596, 'e'=5 =>70097. So mp[70097].push(2). And also "co" etc. For "coding": "co" appears, but "code" not.
Thus after building, mp[70097] vector contains [1,2]. For "co": Let's compute encoding for "co": c=3, o=15 => 3*27+15=96. So mp[96] contains indices: from "code": [1], from "coder": [2], from "coding": [3] (since "coding": c=3, o=15 => 96). So vector [1,2,3]. Query: L=1,R=3, pattern "code": key=70097 -> vector [1,2] -> binary search gives 2. Pattern "co": key=96 -> vector [1,2,3] -> count 3. Works.
Now consider case where pattern length >10? Not in constraints, but we handle.
Now we need to ensure that we use 64-bit (unsigned long long) for key, as 27^10 fits.
Now, one more nuance: The input strings are all lowercase letters; we subtract 'a' and add 1 to map 'a' to 1, 'z' to 26. That's fine, 0 is not used.
Now, what about empty string? Not allowed.
Now, memory: seen set per string with up to 55 entries, each entry is a uint64_t, negligible.
Now, potential collision of encoding? Not with base 27 because the maximum is 27^10 -1 < 2^48. So unique.
Now, could there be any issue with encoding for strings that have leading characters? Not.
Now, we need to ensure that the pattern encoding matches exactly the substring encoding; e.g., substring "a" encodes to 1, but also substring "aa" encodes to 1*27+1=28, distinct. Good.
Now, we should also consider if the pattern could be longer than 10? If so, we output 0, but we need to read it anyway. But we can encode anyway, but then the encoding may collide with some substring? For example, if pattern length is 11, its encoding could be a number that equals some encoding of a different shorter string? Since base-27 representation is unique regardless of length (as long as we don't have leading zeros), but if we allow longer strings, the encoding could be larger than 27^10, but could it equal some encoding of a shorter string? No, because if you have a shorter string, its encoding is less than 27^len, and a longer string's encoding is at least 27^(len) times the first digit, which is > 27^len, so cannot be equal. Actually consider "a" = 1; "a"+"a" with a leading zero? There's no zero digit because we use 1-26.