After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique.
For a given sentence, the cipher is processed as:
Convert all letters of the sentence to lowercase.
Reverse each of the words of the sentence individually.
Remove all the spaces in the sentence.
For example, when this cipher is applied to the sentence
Kira is childish and he hates losing
the resulting string is
ariksihsidlihcdnaehsetahgnisol
Now Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t.
The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000.
Output
Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those.
Examples
Input
30
ariksihsidlihcdnaehsetahgnisol
10
Kira
hates
is
he
losing
death
childish
L
and
Note
Output
Kira is childish and he hates losing
Input
12
iherehtolleh
5
HI
Ho
there
HeLLo
hello
Output
HI there HeLLo
Note
In sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.
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 need to solve a problem: Given a ciphered string t of length n (lowercase letters, no spaces). The original sentence is composed of words from a given list. The cipher process: convert to lowercase, reverse each word individually, remove all spaces. So t is the concatenation of reversed lowercase versions of each word in the original sentence, in order.
We are given list of words wi (uppercase/lowercase). When deciphering, we must use words from this list (any number of times) to form a sentence that, after applying the cipher, yields t. Output any valid original sentence (with spaces between words, and preserving the original case of the words as given in the list, i.e., we output the words themselves as they appear in the list? Actually the original sentence is composed using only words from the list. They have case as given. So we output the words with the case they have in the list. (But note: the cipher first converts all letters to lowercase before reversing. So the case of the word in the original sentence matters only for output, not for matching the cipher. When constructing, we consider the word's lowercase version, reversed, to match a segment of t.)
We need to find a sequence of words such that the concatenation of (lowercase(word) reversed) equals t. We can use any word any number of times.
This is essentially a segmentation/dynamic programming problem: We have a target string t of length up to 10000. We have a dictionary of up to 100,000 words, total length up to 1,000,000. For each word, we compute its "reversed lowercase" representation (call it rw = reverse(lowercase(word))). Then we need to cover t with a sequence of these rw's. Since any solution exists.
We need to output the original sentence, meaning the sequence of words (with their original case, and spaces between). So we need to reconstruct the segmentation.
Constraints: n=10,000, m=100,000, total length of words 1e6. Straightforward DP: For each position i from 0 to n (0-indexed, i being start of next segment), we want to know if we can segment from i to end. Then we need to find a word such that t[i:i+len(rw)] == rw, and then dp[i] true if dp[i+len(rw)] true. Base: dp[n] = true.
But we need to output any solution. So we can do DP forward or backward. Since n is only 10k, we can store dp boolean array of size n+1. However, the number of words is large (100k) and each word length up to 1000. We could precompute all words' reversed lower representation and group by length? But the total length of all words is 1e6, so we could for each position i, try all words? That would be O(n*m) worst-case, impossible.
We need a more efficient way to check which words can match starting at position i. Since t is fixed, we can use a Trie of reversed words. Or better, we can use a hash map from reversed strings to list of original words? But note: t is only 10000, we could for each starting position i, generate substrings of increasing length (up to max word length, say L max) and check if that substring exists among the set of reversed words. However, the total number of substrings of t is O(n * L) where L max is the maximum word length. Since total length of words is 1e6, but maximum word length is <=1000, and n=10000, worst-case n*L = 10 million (if L=1000, that's 10 million). That's acceptable? 10 million substring checks is maybe okay in C++ with a hash set; but we also need to store which word(s) correspond to that reversed string. But note: There can be multiple words that map to the same reversed lowercase string (different case, e.g., "hello" and "HeLLo" both reversed lowercase = "olleh"). In that case, any is acceptable; we can choose arbitrarily. So we can map reversed string to any one original word (maybe the first encountered). But we need to output the original words; we can store one representative.
However, we must be careful: The original word list includes both uppercase and lowercase letters. The reversed lowercase representation is the same for words that differ only in case. But output can be any word from list; we can output any of them that match. So mapping reversed string to a list or just one is fine.
But the approach: For each position i from 0 to n-1, we want to find all lengths L such that t.substr(i, L) is in the set of reversed words. Then we can set dp[i] = true if any dp[i+L] true. To reconstruct, we can store a transition: next[i] = L (or the word used). Since we only need any solution, we can store the word index used.
But we must be careful: The set of reversed words may have duplicates. Total number of distinct reversed strings could be up to m, but likely less. We can store a map from string to word index (maybe first seen). Also need to consider that the word length could be up to 1000, so we need to bound L to at most n-i and also at most maxlen (maximum length of any word). So we can precompute maxlen.
Now, for each i, we can iterate L from 1 to maxlen while i+L <= n, building the substring incrementally and checking in a trie/hash set. Checking a substring in a hash set requires extracting the substring (which is O(L) if we construct a new string each time). But we can do it smarter: we can precompute a rolling hash? Or we can use a Trie for the reversed words and walk it as we extend the substring from i. That would be O(total characters examined across all positions) if we traverse from each i until we hit nodes that are not in trie or we exceed maxlen. Since n=10k, maxlen=1000, worst-case we might examine n * average depth? But if we for each i, we walk down trie, we might need to traverse up to maxlen characters, so total operations O(n * maxlen) = 10 million, which is okay. Actually worse: For each i, we will traverse characters until no match; but that could be up to maxlen each time, so about 10 million. That's fine.
Alternatively, we can precompute a hash set of all reversed words, and for each i, for L from 1 to maxlen, compute the hash of t[i:i+L] quickly using rolling hash to avoid O(L) per substring. But Python may be slower. Since we are to produce a solution, we can choose Python implementation and try to be efficient. However, constraints: n=10000, maxlen=1000, m up to 100k, total word length 1e6. In Python, O(n * maxlen) = 10 million operations, which might be okay if optimized (e.g., using a trie with dicts and early break). But building a trie of all reversed words: total characters = sum of lengths of all reversed words = total length of words <= 1e6, so memory is okay. Then for each position i, we walk from i, for j from i while j < n and current node has child t[j], and continue until we hit a node that might be end of a word. For each such end, we check if we can set dp[i] if dp[j+1] is true. But we need dp computed from the end backward. So we can process positions from n downwards, and for each i, we walk forward building substring via trie. That would be O(total matches) possibly but we can early stop when no child. However, worst-case we may traverse all characters anyway. That's 10 million steps; in Python it's likely fine (maybe ~0.1-0.2 seconds per million? Actually Python can handle ~50 million simple operations per second? It depends. But 10 million dict lookups might be okay within time limit (typical 2 sec?). Should be safe. But let's think: In the worst-case scenario, the trie is dense? Actually each node is a dict mapping char to node; for each character we do a dict lookup. 10 million lookups is fine. Also we must consider that for each i we may walk up to maxlen but often less if trie branch ends earlier. So overall operations should be less than 10 million * constant.
But is there a more efficient method? With Python, we also need to handle building the reversed strings: for each word, we need to compute rev = word.lower()[::-1]. That's O(total word length). That's okay.
One important nuance: The words in the list can be up to length 1000, but total length 1e6. So the trie might have up to 1e6 nodes; each node is a dict, memory may be high but manageable (maybe 200 MB?) Actually in Python, each dict overhead is large. But we can implement a trie using arrays? Or we could use a hash map keyed by substring? But maybe we can use a simpler approach: Since n is only 10000, we can precompute all substrings of t up to maxlen and store them in a set? But total substrings up to n * maxlen = 10 million, each substring length up to 1000; storing them all would be huge. Not good.
Better: We can use DP with a hash map of reversed words. For each position i, we can generate the substring incrementally by extending a string builder (like using a list and appending) and check membership. But generating a new substring for each L would allocate many strings, causing overhead. So trie is better because we can share prefix.
But maybe we can use a set of reversed words, and for each i, we iterate L from 1 to min(maxlen, n-i) and check if t[i:i+L] is in set. That would allocate a substring slice each time (which creates a new string in Python? Actually slicing a string creates a new string, which is O(L) memory copy). That would be O(n * maxlen^2) time due to copying? Wait: If we do t[i:i+L], it creates a new string of length L, which is O(L) to copy. So total time O(sum over i of sum over L of L) = O(n * maxlen^2) if we do naive loops. That's too high. So we need a more efficient method.
Thus trie is good: we can walk without copying.
Alternative: Use rolling hash (e.g., polynomial hash) to compute hash for each substring in O(1) after preprocessing. Then we can check if the hash exists in a set of hashes of reversed words. But we must handle collisions; we could store the actual strings for verification or use double hash. But Python's built-in hash of strings is not rolling; we'd need to compute manually. That could be done, but also we need to reconstruct the word used, so we need to map from hash to a word. There is risk of collisions but double hashing reduces it. But simpler: use a Trie.
Let's design a Trie where each node has:
children: dict char->node
word_index: optional (index of a word that ends at this node) (there may be multiple; we can store one, or a list; we just need any word that matches; we can store the index of the first word encountered).
When we reverse and lowercase a word, we add it to the trie.
After building trie, we do DP from n down to 0:
dp = [False] * (n+1)
dp[n] = True
next_word = [None] * n # store index of word used for segment starting at i, maybe also length
For i from n-1 down to 0:
node = root
for j in range(i, min(n, i+maxlen)):
ch = t[j]
if ch not in node.children:
break
node = node.children[ch]
if node.word_index is not None and dp[j+1]:
dp[i] = True
next_word[i] = node.word_index
# Possibly we can break? But if we want any solution, we can stop once we find one.
# However, we might need to consider multiple possibilities? Not needed, we just need any.
# But careful: If we break early, that might be okay but we need to ensure we don't miss a solution if later word would also work? Since we only need any solution, we can stop as soon as we find a word that leads to a valid suffix. However, we must ensure dp[j+1] is already computed (since we are processing i descending, j+1 > i, so dp[j+1] is already known). So we can set dp[i] true and break. This is fine. But caution: There might be multiple words that end at this node (if multiple words share same reversed string), but we store one index.
break? Actually we should break after we set? But we are inside loop over j. If we find a word that works, we can set dp[i] = True, record the word, and break out of the j loop. However, we also need to consider that maybe a longer word also works, but we only need one. So it's fine to break the loop over j entirely. But we need to break both inner loop and then skip further? We can break out of the for loop using a flag or just return after setting? But we are in a for loop; we can set dp[i] and break (the inner loop). But after breaking, we still continue with next i? Actually we can just break and go to next i; no need to check other j. However, we must ensure that we don't break too early before checking a word that ends later? Since we break only after we set dp[i] true, that's fine. But we need to be careful: the order of j is increasing. If we find a word at some length that leads to a valid suffix, we can take it. So we can break. That's okay.
But note: We have to store next_word[i] = node.word_index. However, we also need the length of that word to reconstruct? Actually we can compute length from the word's original length, but we have the word index, so we can get the original word and its reversed length = len(rev). That rev length is the segment length. For reconstruction, we need to know how many characters to skip. So we can either store length or the word index; from the word index we can get rev length by storing an array rev_len[i] = len(rev of word i). But careful: The word index we store might be for a word whose reversed representation matches the substring from i to j inclusive (length = j-i+1). So the length is determined by j+1 - i. But we have j known in the loop. So we can store j+1 as next position, or store the word index and also the length? Since we break after finding, we could store next_pos[i] = j+1 and word_used[i] = node.word_index. That would help reconstruction.
So DP approach:
maxlen = max(len(word) for word in words) (maybe need to compute rev length; but the reversed length equals original word length because reversing doesn't change length).
We'll store rev_word[i] = reverse(lower(word_i)). But we only need for adding to trie. Also we might store original_word[i] = word_i (as given, with case). For DP reconstruction, we need original word strings.
Now, building trie:
root = Node()
for idx, rev in enumerate(rev_words):
node = root
for ch in rev:
if ch not in node.children:
node.children[ch] = Node()
node = node.children[ch]
if node.word_index is None:
node.word_index = idx
# If there are multiple words with same rev, we can keep the first; any is fine.
for i in range(n-1, -1, -1):
node = root
for j in range(i, min(n, i+maxlen)):
ch = t[j]
if ch not in node.children:
break
node = node.children[ch]
if node.word_index is not None and dp[j+1]:
dp[i] = True
used_word[i] = node.word_index
next_pos[i] = j+1
break
Since we guarantee solution exists, dp[0] will be True.
Now reconstruct:
i = 0
words_list = []
while i < n:
idx = used_word[i]
words_list.append(original_words[idx]) # original words as given
i = next_pos[i]
print(' '.join(words_list))
Edge Cases:
The sample includes trailing space? In output they have a trailing space? The sample output: "Kira is childish and he hates losing " (with space at end). Actually the problem statement output shows a space at the end, but usually we might output without trailing space? However, note that they printed one line with a trailing space. The problem statement: "Print one line — the original sentence." Usually they don't require trailing space, but sample shows it. Might be due to formatting. Better to output without trailing space (join with spaces). But maybe they expect trailing space? In the second sample output: "HI there HeLLo " (space at end). It says: "Output: HI there HeLLo ". So they definitely include trailing space. However, many judges accept both. But to be safe, we can output a trailing space? Actually the join will produce "word1 word2" without trailing space. To produce trailing space, we could do ' '.join(words) + ' '. But the problem statement: "Print one line — the original sentence." Typically a sentence doesn't have trailing space. But the sample shows space at end, maybe because they printed each word followed by space. It's ambiguous. Usually in such problems, they accept any solution, and whitespace at end may be ignored. I think it's safe to output with spaces between words and no trailing space. But the sample output includes a space after last word. Could be that they used print(' '.join(words)+' ') but we can reproduce exactly by adding a space after each word? Actually they likely printed each word with a space after, including last. Let's check the first sample: Output: "Kira is childish and he hates losing " There's a space after losing. In many Codeforces problems (I think this is from Codeforces 633B? Actually it's from Codeforces 633B? Possibly problem "Spy Syndrome 2"? I recall a CF problem with similar description). Usually the output is the original sentence with spaces; trailing space might be accepted but not required. I'll output with join and then a space? However, joining with spaces yields no trailing space. To match sample, we could add an extra space at the end. But it's likely not necessary. I'll just output join with spaces, and maybe add a trailing space? Let's decide: In competitive programming, judges usually ignore trailing whitespace. So both are fine. I'll output using print(' '.join(words)) without trailing space.
Now, complexity: Building trie: O(total length of words) up to 1e6. DP: For each i, we walk trie up to maxlen or until mismatch. In worst-case, for each i, we may walk all maxlen, and each step does a dict lookup. That's up to 10 million operations. Python can handle it if optimized.
But note: The dictionary may be deep and each lookup is O(1) average. 10 million is fine.
However, there is a subtlety: The number of words is up to 100k, and total length up to 1e6, but maxlen could be 1000. That's okay.
But we must also ensure memory for dp arrays: n+1 ~ 10001, fine. For trie nodes: each node is a dict, and each node corresponds to a character in the trie. The total number of nodes is at most total length of distinct reversed strings? Actually we add each reversed word; the trie may share prefixes, so nodes <= total characters (1e6). Each node is a dict object; Python dict overhead is high (~72 bytes per empty dict? plus keys). 1e6 nodes would be ~72 MB just for dict objects, plus overhead for the Node objects (we can store children as dict inside node). That could exceed memory limit (typically 256 MB). 1e6 nodes * (say 56 bytes for dict + 56 for node) maybe > 100 MB. Actually we can reduce by storing children as a simple array of size 26? Because characters are lowercase letters only (a-z). Since after lowercasing, the reversed strings consist only of lowercase letters (a-z). So we can use a fixed array of 26 integers for children, each integer being index of child node in a global list. That would be more memory efficient.
We can implement the trie as a list of nodes, each node: an array of 26 ints (maybe using list of -1), and a word_index. This would be memory: each node: 26 ints (each int 28 bytes? Actually Python int is large ~28 bytes, so 26*28 = 728 bytes per node, too large). Better to use arrays of small ints via 'array' module or use list of ints? That's still big. Alternatively, we can use dictionaries because many nodes will have few children. But total nodes 1e6, each node as a dict might be memory heavy but maybe still under limit? Let's estimate.
Suppose we have 1e6 nodes. Each node as a dict: A new empty dict uses about 72 bytes (Py3.8, 64-bit). Each entry in dict (key-value) adds additional overhead. But if each node has average degree maybe 1-2. But each node also holds the dict for children and a word_index. We could store children as a dict mapping char to node index. For each edge, we store a key (character) and value (node index). That adds overhead per edge. So total memory may be high.
Given constraints (total word length 1e6), it's plausible but we should be careful. However, typical Codeforces solutions in Python use a trie with dict and pass for this problem (I recall a problem "Spy Syndrome 2" with similar constraints). Many Python solutions use a trie with dict and pass because m=100k, total length 1e6, but the number of distinct reversed words might be less than m, and the trie might be smaller because words share prefixes? Actually the reversed words could be diverse; but still nodes <= total characters. 1e6 nodes with dict could be heavy; maybe the test data ensures not all 1e6 characters are distinct nodes? They can be, if all words are distinct and no sharing, then each word is a path of length L, each node is unique (except root). So worst-case nodes = total characters = 1e6. Each node: a dict, and each dict may have only one entry (if it's a chain). But dict still overhead. Possibly memory exceed 256 MB? Let's approximate:
Each dict object overhead ~56 bytes (I think in CPython 3.8, an empty dict is about 72 bytes, plus maybe some). Actually let's check: In Python 3.8, sys.getsizeof({}) returns 64 bytes on 64-bit? I think 72. For simplicity, assume 72.
For each node, we also have a word_index (maybe -1 or None), stored as an attribute in a class instance. The class instance itself has overhead: dict? Actually if we define a class Node with slots we can reduce overhead. Without slots, each instance has a dict which is a dict itself, which is heavy. But we can use slots to store children dict and word_index. However, the children dict is still a separate dict.
Better approach: Use an array/global dictionary of children using adjacency lists stored in arrays: we can implement the trie as two parallel arrays: "next" for each node, but since the alphabet is small (26), we can use a list of dicts only for edges; but still high overhead.
Alternative: Since n is only 10000, we could use DP with hashing: Precompute hashes for t, and for each word, compute its reversed hash and store in a hash table mapping to word indices, but we need to handle collisions. This would avoid a huge trie. With n=10000 and maxlen=1000, we could for each position i, generate substrings up to maxlen and compute rolling hash O(1) per substring, and check if that hash is in a set. That would be O(n * maxlen) = 10 million hash computations, which might be okay. We'll need to store a map from hash to a list of (length, word_idx) maybe. But since we only need any, we can map from (hash, length) to word_idx. However, we need to handle collisions; we can use double hash or use Python's built-in hash of strings? But we can't rely on substring slices because they allocate new strings. But we can compute polynomial rolling hash modulo large primes and use two mod to avoid collisions. This might be simpler and memory efficient. The map would store for each (hash1, hash2, length) maybe to word index. But number of distinct reversed words is up to m=100k, but total entries = number of words. We can store in a dictionary keyed by the reversed string itself? That would be too large? Actually we could store the reversed strings themselves in a set? But then to look up substring we would need to create substring string; that's the original issue. So we need to avoid creating substrings. Rolling hash avoids creating substrings.
Plan:
Preprocess t with two rolling hash arrays (or one with large mod) to allow O(1) substring hash queries.
Compute for each word w: rev = w.lower()[::-1]; compute its hash (same rolling function) and store mapping from (hash_val, len(rev)) to (word_idx). Since collisions possible, we can use double hash (two mod primes). So the key will be a tuple (h1, h2, length). Then it's collision-free for practical purposes.
Then DP: for i from n-1 down to 0, for L from 1 to min(maxlen, n-i), compute hash of t[i:i+L] using rolling hash, and check if that (h1, h2, L) is in the map. If yes, and dp[i+L] true, set dp[i] true, record word index and next position = i+L, break.
This loop is O(n * maxlen) = up to 10 million, each step does a hash computation and dictionary lookup (O(1)). That's likely fine in Python if optimized.
But careful: computing rolling hash for each L naively from scratch each time would be O(L) if we compute incremental hash; but we can precompute prefix hash and then compute substring hash in O(1) using formula: h = (pref[r] - pref[l] * pow_base^(r-l) mod M). So we can precompute prefix hashes for t and also powers of base modulo M. Then for each (i, L) we compute h = get_hash(i, i+L). That is O(1). So total O(n * maxlen) operations.
Thus we avoid trie memory issues. Let's estimate: n=10000, maxlen=1000 -> 10 million iterations. In Python, 10 million simple operations (arithmetic, dictionary lookups) might be borderline but likely okay with good optimization (using PyPy). Typically PyPy can handle ~50 million simple operations per second? Actually PyPy may be slower but okay. Codeforces time limit maybe 2 seconds? However, 10 million is fine, especially if we break early when we find a match; but in worst-case we might need to check many lengths before finding a match? But we can break after finding one; but we still need to check lengths in increasing order? If we want any solution, we could check all lengths; but we might stop at the first that works. However, if the first few lengths don't work, we might need to continue. In the worst-case, maybe we need to check many lengths before hitting a match. But we can try to optimize by iterating lengths that actually correspond to existing reversed words of that length? But we can still have up to maxlen checks. So worst-case 10 million.
But we can also try to reduce by only checking lengths for which there exists a word of that length. We can precompute a set of lengths present among reversed words. That could reduce the number of checks. Because maxlen could be 1000, but if there are only e.g., 10 distinct lengths, we can try only those lengths at each i. That would be O(n * #distinct_lengths). But in worst-case, distinct lengths could be up to 1000 if there are words of many different lengths. However, with total length 1e6 and each word length up to 1000, there could be up to 1000 distinct lengths. So not helpful.
Alternative: Use the trie approach but with efficient memory using arrays of ints in a flattened representation? Could be implemented in Python using list of dict for edges only, not per node dict? Actually we could store the trie as a list of dictionaries of char to next node index. This is similar to using dict but we still have per node dict. However, we can store edges in a global dictionary keyed by (node_index, char) -> next_node. That would reduce per node overhead? But then we need to store mapping for each edge. Possibly memory similar.
Given the rolling hash approach seems simpler and memory-light, we'll adopt that. However, we must be careful about hash collisions. Use two mod primes (like 109+7 and 109+9) or maybe a larger single mod? But collisions could happen; using double hash reduces probability to negligible. In competitive programming, it's accepted.
But there's a nuance: The ciphered text is only lowercase letters, so we can map 'a' to 1, ... 'z' to 26. We'll choose base = something like 91138233? Actually base should be > alphabet size, say 91138233? But we need modulo operations; better to use base like 131 or 91138233? For mod, we use a prime ~1e9. We can use base = 91138233? Actually base should be less than mod. Usually 91138233 is large, but we can use 131, 137, etc. We'll use base = 91138233? That's huge; computing powers modulo mod with such a large base may cause overflow but Python handles big ints. However, using base as small number like 131 is fine. We'll use base = 91138233? Not needed. We'll pick base = 131.
Now compute:
MOD1 = 1000000007
MOD2 = 1000000009
base = 131 (or 91138233? Actually 131 is small, works)
Precompute arrays:
pow1[0..n], pow2[0..n]
pref1[0..n], pref2[0..n]
where pref1[i] = hash of t[0:i] (prefix length i). Standard: pref1[0] = 0; for i from 0 to n-1: pref1[i+1] = (pref1[i]*base + (ord(t[i]) - ord('a') + 1)) % MOD1.
Then substring hash for [l, r) (0-indexed, l inclusive, r exclusive):
hash1 = (pref1[r] - pref1[l] * pow1[r-l] % MOD1 + MOD1) % MOD1.
Similarly for MOD2.
Now for each word w:
rev = w.lower()[::-1]
compute its hash (h1, h2) using the same method, but we can compute iteratively: for ch in rev: h1 = (h1*base + code(ch)) % MOD1, etc.
length = len(rev)
map[(h1, h2, length)] = idx # store word index (any)
But careful: There may be multiple words with same rev (identical reversed lowercase). If we store only one, that's fine.
But what about collisions: Two different strings (different rev) could produce same (h1, h2, length) by chance, but probability extremely low; we can accept.
maxlen = max(len(w) for w in words) # original length = rev length
For i from n-1 down to 0:
h1 = pref1[i] # not exactly; we'll compute substring hashes incrementally? Actually we can compute for each L.
# But we can iterate L from 1 to min(maxlen, n-i):
for L in range(1, min(maxlen, n-i)+1):
# compute hash of t[i:i+L]
r = i+L
h1 = (pref1[r] - pref1[i] * pow1[L]) % MOD1
h2 = (pref2[r] - pref2[i] * pow2[L]) % MOD2
# ensure positive mod:
if h1 < 0: h1 += MOD1
if h2 < 0: h2 += MOD2 # but using % ensures positive
key = (h1, h2, L)
if key in word_map and dp[r]:
dp[i] = True
used_word[i] = word_map[key] # store word index
next_pos[i] = r
break
But we must compute h1,h2 properly: Actually using % after subtraction may yield negative if not done with %; we can compute: h1 = (pref1[r] - pref1[i] * pow1[L] % MOD1 + MOD1) % MOD1. We'll do that.
Now, we need to be careful about potential high number of iterations: For each i, we may loop up to maxlen. 10 million loops. Inside each loop we compute two hashes, do dictionary lookup. That's fine.
But we can optimize: Instead of iterating L from 1 upwards, we could iterate over possible lengths that actually exist for words, and check if the substring of that length matches. That may reduce loops if few lengths. But we can precompute a set of lengths, and for each i, iterate over those lengths that are <= n-i. If number of distinct lengths is small, that's faster. But worst-case, it could be up to 1000; same as maxlen. So not much difference.
Potential speed-up: Since we only need any segmentation, we could also perform DP forward with greedy? Not necessarily.
Also note: The DP only uses dp[r] which is already computed because r > i (since we process i descending). So we can break on first match.
Now, memory for word_map: up to 100k entries; each key is a tuple of three ints, value an int. That's fine.
Now, we need to compute hash for each reversed word. That's O(total length of words) = 1e6, fine.
Now, careful: The words may be long (up to 1000). Computing their hash by iterating through characters is fine.
One nuance: We compute hash using the same base and mod as for t. So we need pow1 and pow2 up to maxlen (which is max word length, at most 1000, but also n=10000 so we need up to n for computing t substring hashes? Actually we need pow array up to n because we compute substring of length up to n. So we compute pow up to n.
Now, potential issues: Since we compute substring hash for each (i,L) using pow array of length up to n, that's fine.
Now, about collisions: It's extremely unlikely. But if a collision occurs, we might get a false positive: t[i:i+L] matches a key for a different word, and dp[r] is true, leading to a segmentation that doesn't correspond to actual words (the actual string may not equal that word's rev). However, we assume probability is negligible and accepted. If we want absolute correctness, we could verify by actual string comparison when we find a candidate (maybe using stored reversed string). But that would require storing rev strings (or maybe just the original word?) Actually we could store rev string for each word? That would be memory heavy (total length 1e6, storing strings anyway). But we can store the reversed string as a key for word_map instead of hash; but then we need to lookup using substring which we would have to create. So not good.
Alternative: Use double hashing but also store the reversed string in the map for collision resolution? But we could store a list of words for each (h1,h2,length) and then verify using the actual rev string from the word if needed. But that would require comparing the substring t[i:i+L] with the stored rev string. To compare, we could extract the substring t[i:i+L] (which creates a string of length L) and compare. That would cost O(L) per candidate, which might be okay if we only do it for successful dp transitions. The number of successful transitions equals number of words in the output, which is at most n (since each word length at least 1) and n=10000, so total extra comparison cost is O(total length of output) ~ n. So we can do that. But we would need to store the reversed string for each word. That's total 1e6 characters, which is fine. We can store rev_strings list. Then in DP, when we find a key match, we can check if t[i:i+L] == rev_strings[word_idx] to confirm; if not, we continue. But we must also handle multiple words with same hash, but we could store a list per hash. Actually simpler: We can store the hash map from (h1,h2,length) to a list of word indices that have that hash. Since collisions rare, list size small. But we can also store just the first word; but if collision occurs, we might get wrong word that doesn't match the substring, and then our segmentation would fail later? Actually if we use a wrong word, we would still need to ensure that the segmentation yields correct t. If we choose a word whose rev string doesn't match t[i:i+L], but the hash matched by accident, then when we later try to output, we would be using a word that doesn't actually correspond to that segment. However, we would still produce a sequence of words that we claim is original sentence, but if we output it, the judge would compare the cipher of that output to t? Actually the problem says "It is guaranteed that at least one solution exists." They ask to output any original sentence that matches. If we output a sentence that doesn't produce t, it would be wrong. So we must ensure our segmentation is correct. Therefore, we cannot rely on hash alone without verification if collisions possible. Even if collisions are extremely rare, it's not safe for judged solution unless we verify. Since we are coding for a contest, we could assume that double hash is sufficient, but some problems require exact matching. Safer is to verify the substring matches the actual reversed word. Since the number of times we verify is at most number of words in output (maybe up to 10000) and each verification string comparison is O(L), total O(n). That's fine. So we can store the rev strings and do a direct compare only when dp[i] gets set. That ensures correctness.
But we need to be careful: There might be multiple words with same rev string (identical after lower and reverse). In that case, hash map might point to any. That's fine; all are valid. However, if two different rev strings have same hash, we need to pick the correct one. So we should store a list per hash and then iterate to find one that matches t[i:i+L] and also leads to a valid suffix. Since collisions are rare, the list size would be 1 most of the time; but for safety, we can store list and iterate.
Alternatively, we can avoid hash entirely and use a Trie with Python, but memory concerns. Let's evaluate memory of trie more carefully.
If we implement trie nodes as objects with slots = ('children', 'word_idx'), where children is a dict. Each node: slots reduces instance dict overhead; each node will have a children dict (which is separate object) and an integer word_idx. Rough memory: Node object with slots has no dict, only references to its attributes. The slots typically store references; each attribute is a reference (8 bytes). So Node may have two references: children (to dict) and word_idx (int). That's about 16 bytes plus overhead of object itself (maybe 56 bytes? Actually in Python, an object has a header ~16 bytes? Let's not go deep). The dict children: each dict object overhead plus entries. If each node has average 1 child, each dict might have small number of entries. But still, 1e6 nodes would be huge.
I recall that Codeforces problem "Spy Syndrome 2" (CF Round #633 Div2 B? Actually it's #633B? I'm not sure) but many Python solutions used a trie with dict and passed. However, the constraints: total length of words <= 1e6, nodes up to 1e6. I'd need to test. Perhaps the input is such that number of distinct reversed words is less than that because many words share prefixes? But worst-case could be all words are random, so each path is distinct; the trie could have up to 1e6 nodes. That might be too memory heavy for Python. However, in Codeforces Python memory limit is typically 256 MB. Let's estimate: A dict with one entry: In CPython, dict entry overhead? Actually each dict has an array of entries; but small dict may have 8 slots? The overhead is not linear. Hard to estimate. But I'd lean towards rolling hash approach as simpler and memory-safe.
But we also need to compute rev strings for each word anyway to compute hash. That's fine; we can store them in a list of strings, total characters 1e6, which is ~1 MB for chars (since each char is 1 byte in Python? Actually Python strings are Unicode; each char takes more memory, but 1e6 chars might be ~1-2 MB? Actually Python strings have overhead; each char is at least 1 byte? In Python, strings are stored as either ASCII compact (if all characters are ASCII) using 1 byte per char; so 1e6 chars ~1 MB plus overhead per string. That's okay.
So we can store rev_strings list, and also compute double hashes and map (h1,h2,len) -> list of indices. Then DP: for each i, L, compute hash, look up list, for each idx in list, check if rev_strings[idx] == t[i:i+L] (we can slice t to get substring; that's O(L) but only for candidates that also have dp[r] true). Since we will likely break after first match, the number of substring extractions is limited. However, we might need to extract substring for each candidate until we find one that matches dp[r]. But we can early exit.
But note: t[i:i+L] creates a new string of length L. If we do this for each candidate, and in the worst-case many words share the same hash (like collisions or many identical rev strings), but the number of candidates is at most size of list. Typically small. Also, we could avoid creating substring for each candidate by storing the rev string and comparing character by character without creating a new string? But substring extraction is O(L) anyway and we can just compare t[i:i+L] == rev_str. That's okay.
But we also must consider that in DP loop, for each i, we might try many L values where the key is not present; we do dictionary lookup only. So the substring creation only occurs for matching keys. So total cost of substring creation for successful matches is at most total length of words in output (<= n). However, there could be many false positive hash matches (collisions) that lead to a list of candidates, but those are rare. So fine.
Thus the rolling hash solution is safe and correct.
Let's design in detail.
Steps:
Read n.
Read t (string of length n, lowercase).
Read m.
Initialize list original_words = [] (store as given).
Initialize list rev_words = [] (store reversed lowercase version).
Initialize max_len = 0.
For each word in input:
original_words.append(word)
rev = word.lower()[::-1]
rev_words.append(rev)
max_len = max(max_len, len(rev))
Precompute rolling hash for t:
Choose base = 131 (or maybe a larger random? 91138233? Actually base should be coprime with mod. 131 is fine.)
Actually we can precompute pow up to n_t or max_len? We'll need pow up to n_t for substring hashes; we compute up to n_t.
Compute hash map for words:
We'll use dict: word_map = {} where key = (h1, h2, length) and value = list of indices (or we can store a single index and later verify; but to be safe store list).
For idx, rev in enumerate(rev_words):
h1 = 0; h2 = 0; L = len(rev)
for ch in rev:
code = ord(ch) - 96
h1 = (h1base + code) % MOD1
h2 = (h2base + code) % MOD2
key = (h1, h2, L)
if key not in word_map: word_map[key] = []
word_map[key].append(idx)
Note: For speed, we could store first index only and then if later we find a false positive due to collision, we can fallback to verifying using the stored rev and maybe then try other? But easier to store list.
for i in range(n_t-1, -1, -1):
# We'll try L from 1 to min(max_len, n_t - i)
for L in range(1, min(max_len, n_t - i) + 1):
r = i + L
# compute substring hash
h1 = (pref1[r] - pref1[i] * pow1[L]) % MOD1
h2 = (pref2[r] - pref2[i] * pow2[L]) % MOD2
# Ensure positive (python % yields non-negative)
# key = (h1, h2, L)
key = (h1, h2, L)
if key in word_map:
# For each candidate index
for idx in word_map[key]:
# Verify actual string match (to avoid hash collision)
if rev_words[idx] != t[i:r]: # slicing O(L); but this comparison is also O(L)
continue
if dp[r]:
dp[i] = True
next_pos[i] = r
used_word_idx[i] = idx
break
if dp[i]:
break
# No need to explicitly handle else; if dp[i] remains False, but problem guarantees solution, so it will be set.
Check sample.
Example 1:
n=30, t=ariksihsidlihcdnaehsetahgnisol
words list: Kira (-> arik), is->si? Wait: "is" reversed lower = "si"? Actually "is" -> "si"? But in t: "ariksihsidlihcdnaehsetahgnisol". Let's test: The first word is "Kira": lowercase "kira", reversed "arik". Indeed t starts with "arik". Good.
Second word "is": "is" lowercase "is", reversed "si". t after "arik" is "si" -> "ariksi" (t: arik s i h s... Actually t: "arik s i h s i d... " Wait the sample: "ariksihsidlihcdnaehsetahgnisol". Let's break: "Kira" -> "arik". "is" -> "si". So "arik"+"si" = "ariksi". But the string starts "ariksi...", which matches. Then "childish": lowercase "childish", reversed "hsidlihc". So "ariksi"+"hsidlihc" = "ariksihsidlihc". That matches next: "ariksihsidlihc". Then "and" -> "dna". So "ariksihsidlihcdna". Then "he" -> "eh". So "ariksihsidlihcdnaeh". Then "hates" -> "setah". So "ariksihsidlihcdnaehsetah". Then "losing" -> "gnisol". So final "ariksihsidlihcdnaehsetahgnisol". Works.
Our algorithm should find a segmentation.
Potential issues: The DP might not find the segmentation if we break early in the inner loop? Actually we break after finding a matching word that yields dp[r] true. That's fine because we need any segmentation. However, we need to ensure that if we break after first matching word at position i, that leads to a valid full segmentation. But since we are processing from right to left, dp[r] is already true for some segmentation of suffix. The first word we find that matches and dp[r] true yields a valid segmentation (concatenating that word with the suffix segmentation). So it's correct.
But we must be careful: Could there be a scenario where we choose a word that leads to a dead end later? No, because dp[r] is already known to be true (there is a segmentation for suffix). So it's safe.
Now complexity: The inner loop runs up to max_len per i. For each i, we compute hash and dictionary lookup. That's 10 million. For those keys that exist, we also iterate over list of indices (likely one) and compare strings (slice) only if dp[r] true. In many cases, dp[r] might be false for many lengths; but we check dp[r] before verifying string? Actually we check dp[r] after verifying? In our code, we check if rev_words[idx] != t[i:r]: continue; then if dp[r]: set. So we compute substring t[i:r] for each candidate even if dp[r] is false? That could be wasteful if dp[r] false; we might want to check dp[r] first because if suffix not possible, there is no point verifying string match. So reorder:
if dp[r] is false: continue? But we don't have dp[r] in the loop yet. Actually we can compute r = i+L; if not dp[r]: continue (skip). Because if suffix not possible, we don't need to consider this word. So we can add a condition before key lookup? Actually we need to compute hash to look up key anyway. But we can compute r and check dp[r] first. That's cheap. So we can reorder: for L: r=i+L; if not dp[r]: continue. Then compute hash and proceed. That reduces substring comparisons only for cases where suffix is possible.
Thus:
for i in reversed range:
for L in range(1, min(max_len, n-i)+1):
r = i+L
if not dp[r]: continue
# compute hash and check.
This is efficient because many dp[r] may be false in early DP stages? Actually dp is filled from end; initially only dp[n] true; as we go backwards, more positions become true. For a given i, dp[r] might be true only for certain r that are start of a valid segmentation. So early on, we may have many false. So this reduces work.
Now, we also need to consider that we need pow arrays up to n. Compute pow array.
Potential memory: t is 10000, fine. word_map: up to 100k entries, each entry storing a list (maybe one element). That's fine.
Now, about handling uppercase/lowercase: We convert word to lower before reversing. Ensure we use .lower().
Now, test with sample 2:
t = iherehtolleh (n=12)
Words: HI, Ho, there, HeLLo, hello
Compute rev:
HI -> "ih" (lower "hi", reversed "ih")
Ho -> "oh"
there -> "ereht"
HeLLo -> "olleh"
hello -> "olleh" as well
We need to segment: t = iherehtolleh
Possible segmentation: HI (ih) + there (ereht) + HeLLo (olleh) -> iherehtolleh, matches. Also HI there hello works (both hello). So our algorithm might choose either.
Our DP from right to left:
At i=0: we try L=1: r=1, dp[1]? Initially only dp[12] true, so skip. We need to find segment that leads to a suffix that is possible. Eventually at i=0, L=2 (ih) will lead to r=2. But dp[2] must be true later? Actually dp[2] will become true if there is segmentation from 2 onward. So order: Process i from 11 down to 0. We'll compute dp[11] etc. dp[11]? substring from 11? t[11] is 'h'? Actually length 12, indices 0-11. t = "i h e r e h t o l l e h"? Let's index: "i"(0), "h"(1), "e"(2), "r"(3), "e"(4), "h"(5), "t"(6), "o"(7), "l"(8), "l"(9), "e"(10), "h"(11). For i=11, maxlen maybe 5? Only possible word of length 1? There is no word of length 1 (since words: lengths: HI=2, Ho=2, there=5, HeLLo=5, hello=5). So dp[11] false. i=10: L=2? but maxlen=5; check L=2 (substring "eh") - no word. L=5? but r=15 >12, so only up to 2. So dp[10] false. i=9: substring from 9: "lh"? Not a word. So eventually i=7? t[7]="o", L=2: "ol"? no; L=5: t[7:12]="olleh" which is rev of HeLLo/hello, length 5, r=12, dp[12]=true, so dp[7] becomes true. Then i=5? etc. So eventually dp[0] becomes true. Works.
Now, we need to ensure that we have word_map entry for (hash of "ih", length 2) mapping to index of "HI". Also for "ereht" length 5 mapping to "there". For "olleh" length 5 mapping to list containing indices of "HeLLo" and "hello". We'll choose whichever first in list. That's fine.
Now, we must also ensure that the rev string comparison t[i:r] works; that's okay.
Now, one more nuance: The word list includes uppercase and lowercase, but the reversed representation is lowercase. So for word "HI", rev = "ih". That's fine.
Now, what about words with length > n? Those can't be used because t length is n, but they could be present in list. In DP we only consider L up to min(max_len, n-i). So they are ignored.
Now, about reading input: the words may contain uppercase/lowercase letters; we must preserve case for output. So store original_words as given.
Now, double-check the total length constraint: total length of all words <= 1,000,000, so storing rev_words list of strings total length 1e6, fine.
Now, about pow array: we compute up to n (max 10000). Could compute up to max_len if we want, but we need up to n for substring of any length. So compute up to n.
Now, possible optimization: We could precompute all substring hashes for all i and all L? That would be O(n^2) which is too high. So we compute on the fly.
Now, implement with careful use of modulo operations.
n = int(input().strip())
t = input().strip()
m = int(input().strip())
original = []
rev = []
max_len = 0
for _ in range(m):
w = input().strip()
original.append(w)
r = w.lower()[::-1]
rev.append(r)
if len(r) > max_len:
max_len = len(r)
# Rolling hash preparation
base = 131
mod1 = 1000000007
mod2 = 1000000009
n_t = len(t)
pow1 = [1]*(n_t+1)
pow2 = [1]*(n_t+1)
pref1 = [0]*(n_t+1)
pref2 = [0]*(n_t+1)
for i,ch in enumerate(t):
code = ord(ch) - 96 # 'a' -> 1
pref1[i+1] = (pref1[i]*base + code) % mod1
pref2[i+1] = (pref2[i]*base + code) % mod2
pow1[i+1] = (pow1[i]*base) % mod1
pow2[i+1] = (pow2[i]*base) % mod2
# Build hash map for words
word_map = {}
for idx, rw in enumerate(rev):
h1 = 0
h2 = 0
for ch in rw:
code = ord(ch) - 96
h1 = (h1*base + code) % mod1
h2 = (h2*base + code) % mod2
L = len(rw)
key = (h1, h2, L)
if key not in word_map:
word_map[key] = []
word_map[key].append(idx)
dp = [False]*(n_t+1)
dp[n_t] = True
next_pos = [-1]*n_t
used_idx = [-1]*n_t
# DP from end
for i in range(n_t-1, -1, -1):
# Determine max L
limit = min(max_len, n_t - i)
for L in range(1, limit+1):
r = i + L
if not dp[r]:
continue
# compute substring hash
# h = pref[r] - pref[i]*pow[L] mod
h1 = (pref1[r] - pref1[i] * pow1[L]) % mod1
h2 = (pref2[r] - pref2[i] * pow2[L]) % mod2
key = (h1, h2, L)
if key not in word_map:
continue
# For each candidate, verify and set
found = False
for idx in word_map[key]:
# Verify actual match
# Could also check length? already by key length.
if rev[idx] != t[i:r]: # direct string compare
continue
# If we reached here, match confirmed and dp[r] is True
dp[i] = True
next_pos[i] = r
used_idx[i] = idx
found = True
break
if found:
break
# Since solution guaranteed, dp[i] will be True.
# Reconstruct
i = 0
res_words = []
while i < n_t:
idx = used_idx[i]
res_words.append(original[idx])
i = next_pos[i]
print(' '.join(res_words))
Now, we need to ensure that the substring extraction t[i:r] is done only when needed and that it's efficient. It creates a new string of length L each time. But we only do it for candidate indices when dp[r] is true, and we break after first success. So total number of extractions is at most the number of words in the output (since each successful step does one extraction) plus maybe a few extra for collisions? But also for candidate indices that don't match due to hash collision, we might extract for each such candidate. That's still minimal. So it's fine.
Now, we should also consider if there are many words with the same hash key but different rev strings (collision). Then we might iterate over them and do substring compare each time. The number of such collisions should be very small. So it's fine.
Now, about speed: The inner loop includes a modulo operation for h1 and h2. We can compute them as:
h1 = (pref1[r] - pref1[i] * pow1[L]) % mod1
Since Python's % gives positive, it's fine.
But we need to compute pow1[L] and pow2[L] which are precomputed.
Now, we should also consider using bitwise operations? Not needed.
Now, test with sample:
Input 1:
30
ariksihsidlihcdnaehsetahgnisol
10
Kira
hates
is
he
losing
death
childish
L
and
Note
Our code will read these. Note that there are words "death", "L", "Note" that are not used. That's fine.
We also have max_len = max length among these words: probably 7? Actually "childish" length 8? Actually "childish" is 8 letters? c h i l d i s h -> 8, reversed length 8. So max_len=8? Check: "losing"=6, "hates"=5, etc. So max_len=8. So for each i, we loop at most 8 lengths, which is trivial.
Now, DP should find segmentation.
Now, potential pitfalls:
The words may include non-letter characters? The problem says only uppercase and lowercase English letters. So fine.
The cipher text is all lowercase, so we compute code for 'a' as 1. Ensure mapping: ord(ch)-96 yields 'a'->1, 'z'->26.
Now, one more nuance: The DP we wrote checks dp[r] before computing hash. This is beneficial. However, there is a subtlety: dp[r] may become true later for i>r? But we process i from n-1 down to 0, so when processing i, dp[r] for r>i has already been computed (since r > i). So that's fine.
Now, regarding the reconstruction: used_idx[i] is set only when we break. Since dp[i] true, used_idx[i] is set. So reconstruction works.
Now, check sample 2 output: We output words with spaces. Should we include trailing space? The sample includes trailing space, but we can ignore. It's fine.
Now, about reading: The input lines may contain trailing newline, .strip() removes.
Now, potential performance: The DP double loop (i from 0 to 9999, L up to max_len) with early continue if dp[r] false will be efficient. In worst-case, many dp[r] may become true for many positions, but that's okay.
Now, test with worst-case: n=10000, max_len=1000, dp[r] maybe true for many r? Actually if there is a solution, dp might be true for many positions (like many segmentations). But still we will for each i check up to 1000 lengths; we continue only if dp[r] true. In worst-case, dp could be true for all positions? Possibly if there are many ways. Then for each i, we will compute hash for each L (since dp[r] true) and lookup key. That is 10 million hashes + lookups. That's okay. But we also will for each i, after finding the first match, we break. However, if the first L that matches is at large L, we might compute many hashes. In worst-case, we could compute all L for each i. That's 10 million. Acceptable.
Now, consider Python's speed: 10 million iterations with a few operations might be borderline but likely passes with PyPy (which is often used on Codeforces). I'll test mental: 10 million * (a few arithmetic operations + dict lookup) could be around 0.5-1 second? Possibly. But also building the word_map and reading input is fine.
We can also add minor optimizations: Use local variables for mod, base, pref1, pref2, pow1, pow2, word_map, rev, dp, etc. to avoid global lookups. Use while loops instead of for? Not needed.
We could also precompute an array of possible lengths (like lengths_present = set of lengths of words) and iterate over those lengths instead of all 1..limit. That would reduce iterations if max_len is large but only few lengths exist. For example, if words are all length 1000, then only one length. So we can compute set_len = set(len(rev) for rev in rev_words). Then for each i, we iterate over L in sorted(set_len) that are <= limit. That could significantly reduce loops if few lengths. In worst-case, there could be up to 1000 distinct lengths, which is same as max_len, but the number of lengths is at most max_len, but iterating over a set of 1000 lengths is same as iterating 1..1000, but we avoid generating range and checking dp[r] for all, but we still need to check dp[r] for each L in set_len. That might be similar. However, if max_len=1000 but only lengths like 1,2,3,...1000 all exist, then set_len has 1000 elements, same as iterating over all L. So no big difference. But if max_len=1000 but only a few lengths exist, it helps. So we can do:
lengths = sorted(set(len(w) for w in rev_words))
But careful: The rev length equals original word length, so we can use that.
Then inside DP: for L in lengths: if L > limit: break (since sorted). Then r = i+L; if not dp[r]: continue; compute hash, etc.
This could be faster if lengths set is small, which may be typical. In worst-case, it's similar. Let's adopt it.
We also need to consider that some lengths may be > n, but that's fine as we filter.
Thus:
word_lengths = sorted(set(len(rw) for rw in rev_words))
But we must ensure we have at least one length; okay.
Now, in DP, we will iterate over word_lengths and break when L > limit. Since word_lengths sorted ascending, we can loop.
Now, this reduces loops when number of distinct lengths is small.
Now, one more potential optimization: For each i, we might compute the hash incrementally as we increase L, but with lengths set we don't have consecutive L. So incremental would be messy. So we stick to computing each hash using prefix.
Now, note: The hash computation requires pow1[L] which we have; we can compute quickly.
Now, we must be careful about negative modulo: In Python, (a - b) % mod yields non-negative result. So we can do (pref1[r] - pref1[i] * pow1[L]) % mod1 directly.
Now, we need to ensure that we treat rev_words list and original list correctly.
Now, final code.
But before finalizing, let's consider an alternative: Use a Trie with Python but with memory optimization: we could store children as array of length 26 in a list of lists? But that would be huge per node. Or we could use a dictionary but store only edges, and use a list of dicts: trie = [dict()]; word_at = [None]. Then for each rev word, we traverse, creating nodes as needed. This is similar to earlier. The memory: number of nodes up to 1e6; each node is an index into a list; the list holds dicts and maybe an int for word index. So each dict is separate object. That may be heavy. Rolling hash seems simpler.
Let's test memory: word_map with 100k entries, each entry key tuple of three ints (28 bytes each? Actually Python int is 28 bytes, tuple overhead, etc.) Might be a few tens of MB, still okay. rev_words list of 100k strings, total 1e6 chars, plus overhead per string (49 bytes overhead). Could be ~50 MB. DP arrays etc small. So total maybe 100-150 MB, which is borderline but likely okay for 256 MB. However, Python's memory for 100k strings of average length 10 (since total 1e6) might be ~ overhead 50 bytes each => 5 MB for overhead, plus character storage ~1 MB. So ~6 MB. The word_map: 100k entries; each entry: key tuple (3 ints) ~ 72 bytes? Actually int 28 bytes each => 84 bytes for ints, plus tuple overhead 56 bytes => ~140 bytes; value list object (maybe 56 bytes) plus one element int (28) = ~84; total per entry ~224 bytes. Times 100k => 22.4 MB. So total memory < 50 MB. Good.
Now, consider building word_map: We compute hash for each word. That's O(total word length). That's fine.
Now, one more nuance: We need to compute pow array up to n, but n may be up to 10000; that's fine.
Now, we should handle the case where max_len might be > n, but we only consider lengths <= n-i.
Now, let's think about potential pitfalls with the DP order and break: Suppose for a given i, we iterate lengths in ascending order. We break on first match. That yields a segmentation that uses the smallest possible word (in terms of length) at that position? Not necessarily smallest, but we break when we find any word that leads to a valid suffix. Since we iterate lengths in ascending order, we will pick the shortest word that works (since we check lengths from small to large). That's fine.
But is it guaranteed that there will be a solution if we always pick the shortest? Possibly yes because solution exists. But we must ensure that if we pick the shortest word, the remainder can still be segmented. That's ensured because we check dp[r] before selecting. So it's safe.
Now, one more nuance: We compute dp from end; dp[r] being true means there is at least one segmentation from r to end. So picking any word with that property yields a valid full segmentation.
Now, the break ensures we don't overwrite later if there is longer word also works; that's fine.
Now, check reconstruction: used_idx[i] is set; next_pos[i] set. Good.
Now, output: we print space-separated words. Should we add a trailing space? Not necessary.
Now, we need to be careful about reading input: the ciphered text line may have spaces? It says second line consists of n lowercase English letters — the ciphered text t. So just a string.
Now, potential edge case: n=1, t='a', and there is a word 'A' (lowercase 'a', reversed 'a'). DP works.
Now, check performance on max constraints: n=10000, max_len maybe 1000, distinct lengths maybe up to 1000. Loops: For each i (10000), we loop over lengths (up to 1000) but we only proceed if length in set lengths and <= limit. In worst-case if all lengths from 1 to 1000 exist, then for each i we loop over 1000 lengths. So 10 million iterations. Each iteration we do: if L not in set? Actually we are iterating over the set of lengths directly, so we don't need to check membership. So each iteration: compute r = i+L; if not dp[r]: continue; else compute hash, lookup, etc. So about 10 million times we compute r and check dp[r]. That's cheap.
But note: if dp[r] is false for many lengths, we just continue. That's just a couple of operations.
In the worst-case where dp[r] is true for many lengths, we also compute hash and dict lookup. That's okay.
Now, we must ensure that the dictionary lookup for key that may not exist is efficient. That's O(1) average.
Thus the solution should pass.
Now, let's double-check the hash mapping: We compute hash for rev word using same base and mod. That's correct.
Now, verify with sample:
We'll manually simulate quickly. Not needed.
Now, think about collisions: Suppose two different strings produce same double hash. Then when we lookup key, we get list of indices. We then compare rev[idx] != t[i:r] to filter. So we will only use the correct one. If we have a collision where the incorrect word's rev string is different, but its hash matches; we will iterate over list, check the first maybe incorrect, fail the string compare, then try next if exists. If the list contains only the incorrect word, then the key exists but none match, so we skip and continue to other lengths. So dp[i] might not get set if the only matching hash is incorrect. But there is guaranteed a solution; the correct word's hash should be in the map. If there is a collision where the correct word's hash collides with another word's hash, the list will contain both; we will find the correct one after comparing. So it's fine. The only danger is if the correct word's hash collides with an incorrect word and the incorrect word is first, but we compare and skip, then we find correct later. So fine.
Now, we should ensure that we add the word's index to the list for its hash. So we do word_map[key].append(idx). So for identical rev strings, we have multiple indices; that's okay. For different rev strings that happen to have same hash (collision), we also have multiple indices; we compare to find the correct one.
Now, is it possible that the correct word's rev string is not in the map because we missed adding? We add for each word.
Now, ensure that we compute hash for rev word correctly: Use same base and mod.
Now, one more nuance: The ciphered text t is all lowercase; we treat each char code accordingly.
Now, potential bug: When computing pref arrays, we used ord(ch)-96. That's fine for 'a'=1. But if we use base=131, mod primes, it's fine.
Now, what about the word "L"? It becomes rev "l". In t there might be 'l' as a separate character. Works.
Now, about the reading: Input lines may have trailing spaces? Use .strip().
Now, let's think about multiple test cases? Problem is single test case.
Now, we must output the original sentence: Should we output the words exactly as given, preserving case. Yes.
Now, does the order of words matter? Must match the cipher order. Yes.
Now, test with sample:
Input 1:
30
ariksihsidlihcdnaehsetahgnisol
10
Kira
hates
is
he
losing
death
childish
L
and
Note
Our algorithm:
rev: Kira -> 'arik'
hates -> 'setah'
is -> 'si'
he -> 'eh'
losing -> 'gnisol'
childish -> 'hsidlihc'
and -> 'dna'
others.
DP should find segmentation: at i=0, lengths set includes 2,5,6,8 etc. Let's see: L=2? t[0:2]='ar' no word? Actually 'ar' not a word. L=4? 'arik' is rev of Kira, length 4. dp[4] must be true later. So eventually picks L=4. Then i=4, substring starting at 4: 'si...' L=2 'si' matches 'is' etc. So works.
But we also need to be careful about input size: reading 100k lines; using sys.stdin.readline is fast.
Now, we need to ensure we use .strip() but not .strip() for words? There could be spaces? No, words are non-empty and consist only of letters, so .strip() is fine.
Now, final code.
But before final, consider if there is a scenario where the DP might not set dp[i] because we break early when we find a word that matches hash and dp[r] but after string comparison fails (due to hash collision) and there is no other word in the list that matches? Then we skip that L, but there might be another L that works. Since we break only when we found a match and set dp[i] = True; if we didn't find any match for any L, dp[i] stays False, which should not happen. However, if for some L, we have a key in word_map but all candidates fail string compare (collisions) and we don't set dp[i], we continue to next L. That's fine because we haven't broken. So we need to ensure we only break when we actually set dp[i] (i.e., found a valid word). In the code we have:
if found:
break
So that's correct.
Now, consider that we might have a case where dp[r] is true and key exists, but after iterating all candidates, none matches (due to collisions). Then we continue to next L. So that's fine.
Now, ensure that for each key we have a list; we iterate over that list. If the list is large (e.g., many words with same rev string), that could be many comparisons. But if many words are identical after lower+reverse (different case), then they all are valid, and we can pick the first. But we still need to compare rev[idx] != t[i:r]? Actually if they are identical rev strings, then rev[idx] == t[i:r] for all if it matches, so first will match. So fine. If they are different rev strings but same hash (collision), list size likely 1 (since collisions rare). So okay.
Now, we can further optimize by storing only one index per key, but then we must handle collisions via fallback. Our method with list is fine.
Now, the code.
I'll write the final solution.
But I realize: The problem guarantees at least one solution exists. However, there might be multiple solutions; we output any.
Now, test with sample 2: lengths set: {2,5} (since HI length 2, Ho length 2, there length 5, HeLLo length 5, hello length 5). So set sorted [2,5]. For i=0, limit=12, iterate L=2: r=2, dp[2]? initially unknown; but we process from right, so when i=0, dp[2] might already be true if there is segmentation from 2 onward. So DP will work.
Now, implement.
We need to be careful with the dp list: we use boolean list, but Python's bool is fine. However, to speed, we could use integer 0/1.
Now, code.
Potential improvements: Use array of ints for dp with 0/1. But bool is fine.
Now, consider the case where some words have length 0? Problem says non-empty word, so length >=1.
Now, done.
Let's write final code with function solve().
We'll include at top: import sys
Then.
Now, test with given examples.
I will write code accordingly.
But we must be careful: When we compute pow1 and pow2 arrays up to n_t, we should compute pow1[0]=1, then for i in range(1, n_t+1): pow1[i] = (pow1[i-1]*base) % mod. In loop we already compute as we fill pref; we can compute simultaneously.
Simplify: Initialize pow1[0]=1; for i in range(1, n_t+1): pow1[i] = (pow1[i-1]*base) % mod1; same for pow2. Then compute pref similarly. Or compute in one loop.
n = int(input())
t = input().strip()
m = int(input())
original = []
rev = []
max_len = 0
lengths_set = set()
for _ in range(m):
w = input().strip()
original.append(w)
r = w.lower()[::-1]
rev.append(r)
l = len(r)
if l > max_len:
max_len = l
lengths_set.add(l)
lengths = sorted(lengths_set) # ascending list
base = 131
mod1 = 1000000007
mod2 = 1000000009
n_t = len(t)
pow1 = [1]*(n_t+1)
pow2 = [1]*(n_t+1)
pref1 = [0]*(n_t+1)
pref2 = [0]*(n_t+1)
for i, ch in enumerate(t):
code = ord(ch) - 96
pref1[i+1] = (pref1[i]*base + code) % mod1
pref2[i+1] = (pref2[i]*base + code) % mod2
pow1[i+1] = (pow1[i]*base) % mod1
pow2[i+1] = (pow2[i]*base) % mod2
# Build map from hash to list of indices
word_map = {}
for idx, rw in enumerate(rev):
h1 = 0
h2 = 0
for ch in rw:
code = ord(ch) - 96
h1 = (h1*base + code) % mod1
h2 = (h2*base + code) % mod2
key = (h1, h2, len(rw))
# using dict setdefault maybe faster
if key in word_map:
word_map[key].append(idx)
else:
word_map[key] = [idx]
dp = [False]*(n_t+1)
dp[n_t] = True
next_pos = [-1]*n_t
used_idx = [-1]*n_t
# Process positions from right to left
for i in range(n_t-1, -1, -1):
limit = n_t - i
# iterate over possible lengths
for L in lengths:
if L > limit:
break
r = i + L
if not dp[r]:
continue
# compute hash of t[i:r]
h1 = (pref1[r] - pref1[i] * pow1[L]) % mod1
h2 = (pref2[r] - pref2[i] * pow2[L]) % mod2
key = (h1, h2, L)
lst = word_map.get(key)
if lst is None:
continue
# search for matching word
found = False
# Could optionally check the first one quickly, since collisions rare
for idx in lst:
if rev[idx] == t[i:r]:
# valid match
dp[i] = True
next_pos[i] = r
used_idx[i] = idx
found = True
break
if found:
break
# Reconstruct
res = []
i = 0
while i < n_t:
idx = used_idx[i]
res.append(original[idx])
i = next_pos[i]
print(' '.join(res))
if name == "main":
solve()
Now, test with sample input:
Input 1:
30
ariksihsidlihcdnaehsetahgnisol
10
Kira
hates
is
he
losing
death
childish
L
and
Note
Our code should output something like "Kira is childish and he hates losing" (maybe with spaces but no trailing). Check: The output might be "Kira is childish and he hates losing". That matches.
But the sample output includes trailing space; they may have printed each word with a space after, but it's fine.
Now, Input 2:
12
iherehtolleh
5
HI
Ho
there
HeLLo
hello
Our code will pick the first word for each segment. For i=0, lengths: [2,5]? Actually lengths set: {2,5} (since words: HI=2, Ho=2, there=5, HeLLo=5, hello=5). Sorted [2,5]. At i=0, L=2: substring t[0:2] = "ih". Compute hash, look up key (hash of "ih", length 2). word_map has entries for rev "ih" from word "HI" (and possibly "Ho"? rev "oh" length 2, so not same). So key exists; lst contains index of "HI". Compare rev[HI] = "ih" with t[0:2]="ih" -> true. dp[2]? must be true from DP? We haven't computed dp[2] yet because we process i from right to left; at i=0, dp[2] may not be computed? Actually we process from n_t-1 down to 0. So when i=0, dp[2] has already been computed because 2 > 0. So if dp[2] is true, we set dp[0] true. But is dp[2] true? We need to check the DP process order: We start from i=11 down to 0. So before i=0, we have computed dp[2] because 2 > 0. So dp[2] should be true if there's segmentation from 2 onward. Let's see: We'll compute dp[11], dp[10], ..., dp[2] before i=0. So yes, dp[2] will be set to true if there is segmentation from 2 to end. So that works.
But what if dp[2] is not true? Then we would check L=5. So segmentation will be found.
Now, the algorithm should output "HI there HeLLo" or "HI there hello" depending on which index is first in list for rev "olleh". Since we added words in order: HI, Ho, there, HeLLo, hello. rev for HeLLo = "olleh", hello = "olleh". So both added to same key? Actually key includes hash and length, so both have same hash (since same string) so key is identical. In word_map, for that key we will have a list: first HeLLo index 3, then hello index 4. When we lookup at i=7 (starting "olleh"), we will get the list, iterate over indices; first is 3 (HeLLo), compare rev[3]="olleh" with t[7:12]="olleh" -> true, and dp[12] is true, so we select HeLLo. So output "HI there HeLLo". That matches sample (they output "HI there HeLLo "). So fine.
Now, potential issue: The DP might set dp[i] using a word that matches but later we find a shorter word that also matches? We break on first found. That's fine.
Now, check for correctness for all cases.
But there is a subtle nuance: When we iterate lengths in sorted order, we may pick a shorter word that leads to a segmentation, but what if that segmentation uses words that are not from the list? No, because dp[r] being true ensures that suffix segmentation exists. So it's fine.
Now, think about large words: max_len up to 1000, but n=10000. The lengths set may contain values up to 1000. So loop over lengths may be up to 1000 per i. That's 10 million. Fine.
Now, one more micro-optimization: We can precompute the code array for t to avoid ord() in DP? Not needed.
Now, potential memory: rev list holds strings, each string is a reversed lowercase version. That's fine.
Now, we need to ensure that the pow arrays are computed correctly: pow1[i] = base^i % mod1.
Now, one more check: When computing pref, we used base and code. Ensure we didn't mix up order: For substring hash, the formula should be: hash(s[l:r]) = (pref[r] - pref[l] * base^(r-l)) mod M. That's correct if we built pref as: pref[0]=0; pref[i+1] = pref[i]*base + code. That's standard.
Now, confirm with a small example: t="ab", base=131, code a=1, b=2. pref[0]=0; pref[1]=0131+1=1; pref[2]=1131+2=133. Substring [0,1) should be "a": hash = (pref[1] - pref[0]131^1) = (1 - 0)=1, correct. Substring [1,2) "b": (133 - 1131)=2, correct. Substring [0,2) "ab": (133 - 0131^2)=133, which equals 1131+2, correct. So formula works.
Now, for word hash we compute similarly by iterating characters: h = h*base + code. That yields same hash as if we computed from pref of the word. So consistent.
Now, all good.
Now, think about integer overflow? Python big ints, but we modulo each step, so numbers stay within mod.
Now, we must handle that pow1 and pow2 arrays are computed up to n_t. But L may be up to max_len which <= 1000 and <= n_t, so fine.
Now, could there be a scenario where the DP fails because we use dp[r] as condition before computing hash, and dp[r] is false for some r but there is a word that would make dp[r] true if we later discover? Wait, we process i from n-1 down to 0, so when we are at i, dp[r] for r>i has been computed. However, dp[r] might be false at this time if we haven't found a segmentation for suffix starting at r yet. But could it become true later? No, because we process decreasing i, so all r > i have already been processed (since r > i). So dp[r] is final. So correct.
Now, consider that the dp array may be large (10k+1). Good.
Now, reconstruction: used_idx[i] is set for each i we step. While i < n_t, we use used_idx[i] to get word. Since dp[0] true, this loop will cover entire string.
Now, we should also consider that there could be multiple solutions; we output one.
Now, code final.
But I realize something: When we process lengths in sorted order, we break when found. That means we are effectively picking the shortest possible word at each position (since lengths sorted ascending). That's okay.
Now, let's test with a small custom case.
Case: n=5, t="olleh", words: ["hello"], also "he","llo"? Not needed.
Case: n=3, t="abc", words: ["cba"]? Actually rev of "cba" (lower) = "abc". So word "cBA" works. Output "cBA". Good.
Now, test with multiple words same rev: n=4, t="abba", words: ["ABBA","abba","baba"?]. rev for "ABBA" = "abba", for "abba" = "abba". Both produce same rev. DP will pick first. That's fine.
Now, test with overlapping possibilities: n=5, t="abcde", words: ["edcba"] rev "abcde" length 5, and also ["ab","cde"]? Actually rev of "ab" = "ba", rev of "cde" = "edc", not matching. So only one works.
Now, test where there are multiple segmentations; algorithm picks shortest word at each step due to ascending lengths. That's deterministic.
Now, is it possible that picking the shortest word leads to a dead end later even though dp[r] true? No, because dp[r] being true guarantees a segmentation from r to end. So shortest word works.
Now, we should check that for each i, if there is at least one valid word, then dp[i] will be set. Since we iterate all lengths, and we check dp[r] true and also verify string equality, we will eventually find a word if solution exists.
Now, about the condition "dp[r]" before computing hash: If there is a word that matches t[i:r] and r leads to a valid suffix, but dp[r] is currently false because we haven't found a segmentation for r? But as argued, r > i, and we process i decreasing, so dp[r] should have been set already if there is a segmentation. However, what if the segmentation from r uses a word that starts at r and that word's length extends beyond n? Not possible. So it's fine.
Now, edge case: The word list may contain words that have rev strings that appear as substrings but are not part of any full segmentation. Our DP only selects if suffix is possible. Good.
Now, complexity wise, building word_map: iterating over each character of all words O(total length 1e6). DP: up to 10 million iterations. Each iteration does constant work. Should pass.
Now, I'll produce final answer. ```python
import sys
def solve() -> None:
input = sys.stdin.readline
code
n = int(input())
t = input().strip()
m = int(input())
original = [] # words as given
rev = [] # reversed lower case version
max_len = 0
lengths_set = set()
for _ in range(m):
w = input().strip()
original.append(w)
r = w.lower()[::-1]
rev.append(r)
l = len(r)
if l > max_len:
max_len = l
lengths_set.add(l)
lengths = sorted(lengths_set) # distinct lengths, increasing
# ---------- rolling hash for the ciphered text ----------
base = 131
MOD1 = 1_000_000_007
MOD2 = 1_000_000_009
n_t = len(t)
pow1 = [1] * (n_t + 1)
pow2 = [1] * (n_t + 1)
pref1 = [0] * (n_t + 1)
pref2 = [0] * (n_t + 1)
for i, ch in enumerate(t):
code = ord(ch) - 96 # 'a' -> 1
pref1[i+1] = (pref1[i] * base + code) % MOD1
pref2[i+1] = (pref2[i] * base + code) % MOD2
pow1[i+1] = (pow1[i] * base) % MOD1
pow2[i+1] = (pow2[i] * base) % MOD2
# ---------- map (hash1, hash2, length) -> list of word indices ----------
word_map = {}
for idx, rw in enumerate(rev):
h1 = 0
h2 = 0
for ch in rw:
code = ord(ch) - 96
h1 = (h1 * base + code) % MOD1
h2 = (h2 * base + code) % MOD2
key = (h1, h2, len(rw))
if key in word_map:
word_map[key].append(idx)
else:
word_map[key] = [idx]
# ---------- DP from right to left ----------
dp = [False] * (n_t + 1)
dp[n_t] = True
next_pos = [-1] * n_t
used_idx = [-1] * n_t
for i in range(n_t - 1, -1, -1):
limit = n_t - i
for L in lengths:
if L > limit:
break
r = i + L
if not dp[r]:
continue
# hash of t[i:r]
h1 = (pref1[r] - pref1[i] * pow1[L]) % MOD1
h2 = (pref2[r] - pref2[i] * pow2[L]) % MOD2
key = (h1, h2, L)
lst = word_map.get(key)
if lst is None:
continue
# check candidates (exact string match to avoid collisions)
found = False
for idx in lst:
if rev[idx] == t[i:r]: # full string comparison
dp[i] = True
next_pos[i] = r
used_idx[i] = idx
found = True
break
if found:
break
# ---------- reconstruct the original sentence ----------
res = []
i = 0
while i < n_t:
idx = used_idx[i]
res.append(original[idx])
i = next_pos[i]
print(' '.join(res))