In an attempt to reduce the growing population, Archer was asked to come up with a plan. Archer being as intelligent as he is, came up with the following plan:
If N children, with names C1, C2, ..., CN, are born to parents with names A and B, and you consider C to be the concatenation of all the names of the children, i.e. C = C1 + C2 + ... + CN (where + is concatenation operator), then C should be a substring of one of the permutations of A + B.
You are given the task to verify whether the names parents propose to give their children are in fact permissible by Archer's plan or not.
Input
The first line contains an integer T, the number of test cases. T test cases follow. Each test case stats with a line containing two space separated strings A and B, denoting the names of the parents. The next line contains a single integer N denoting the number of children A and B are planning to have. Following this are N lines, the i'th line containing Ci, the proposed name for the i'th child.
Output
For each test case output a single line containing "YES" if the names are permissible by Archer's plan, otherwise print "NO". (quotes are meant for clarity, please don't print them)
Constraints
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
The lengths of all the strings including A, B, and all Ci will be in the range [1, 40000], both inclusive. All these strings will contain only lowercase English letters.
The combined lengths of all names of children will not exceed the combined length of the names of their parents.
Example
Input:
3
tom marvoloriddle
2
lord
voldemort
cheap up
1
heapcup
bruce wayne
2
bat
man
Output:
YES
YES
NO
Explanation:
Let Y denote the concatenation of names of all the children, and X denote the concatenation of the names of the parents.
Case 1: Here X = "tommarvoloriddle", and Y = "lordvoldemort". Consider Z = "iamlordvoldemort". It is not difficult to see that Z is a permutation of X and Y is a substring of Z. Hence Y is a substring of a permutation of X, so the answer is "YES".
Case 2: Here X = "cheapup", and Y = "heapcup". Since Y in itself is a permutation of X, and as every string is a substring of itself, Y is a substring of X and also a permutation of X. Hence "YES".
Case 3: Here X = "brucewayne", and Y = "batman". As "t" is not present in X, "t" wont be present in any permutation of X, hence the answer is "NO".
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 the problem: Given two parent strings A and B, let X = A + B (concatenation, not necessarily separated by space; the input gives A and B as separate strings, but we concatenate them directly). Given N children names Ci, let Y = concatenation of all Ci in order. Check if Y is a substring of some permutation of X. Equivalent: Is there some permutation (rearrangement of characters) of X that contains Y as a contiguous substring? We need to output YES or NO per test case.
Constraints: T up to 100. N up to 1000. Each string length up to 40000. Combined lengths of children strings <= combined length of parent strings? Actually the problem statement: "The combined lengths of all names of children will not exceed the combined length of the names of their parents." So total length of Y <= length of X. But could be less.
Goal: Determine if Y is a substring of some permutation of X. This is a classic combinatorial string problem.
We need to check if there exists a permutation (i.e., a rearrangement of all characters in X) such that Y appears as a contiguous substring. Equivalent: There exists a way to order the characters of X (i.e., form a string of length |X|) containing Y as a substring. This is essentially a question about whether Y can be embedded into a permutation of X. Since the permutation uses exactly all characters of X, but Y might be shorter. So we need to see if we can arrange the characters of X such that Y appears contiguously, and the rest of the characters (the ones not used in that substring) can be arranged arbitrarily around it.
Let L = |X|, M = |Y|. We need to find if there exists a contiguous block of length M in some permutation of X that equals Y. This is equivalent to: There exists a multiset of characters in Y that is a subset (multiset subset) of the multiset of X, and the remaining characters (X minus the characters used in Y) can be arranged arbitrarily. Since we can place Y anywhere in the permutation, we just need that Y's character count (frequency vector) is <= X's frequency vector (component-wise). But wait, is that sufficient? If Y's multiset is a subset of X's multiset, then we could take the characters needed for Y from X, and then arrange the rest arbitrarily, and place Y as a contiguous block somewhere. However, is it always possible to arrange the rest and also keep Y contiguous? If we have all characters of X, we can always form a string that has Y as a contiguous substring by simply putting Y together and then placing the remaining characters anywhere (either before or after, or both, but they might intermix? To ensure Y is contiguous, we just need to not break Y's characters. So we can construct: prefix (some arrangement of remaining chars), then Y, then suffix (rest of remaining chars). But note: The remaining chars are all characters of X that are not used in Y, but we must use each character exactly once. So we can take any ordering of the multiset of remaining chars as prefix and suffix, but we must decide how to split them. That's always possible: we can put all remaining chars either before Y or after Y, or split between before and after. That yields a permutation of X that contains Y as a substring. However, we must ensure that the remaining chars are arranged in some order; that's always possible. So the condition reduces to: For Y to be a substring of some permutation of X, it is necessary and sufficient that the frequency of each character in Y is <= frequency of that character in X.
But wait, is there any subtlety? For example, consider X = "ab", Y = "ab". Then frequencies: a:1, b:1 in both, condition holds. Permutation of X is either "ab" or "ba". Y = "ab" is substring of "ab" (yes) and also substring of "ba"? "ab" is not substring of "ba". But there exists at least one permutation ("ab") that contains Y as substring. So condition holds, output YES.
Consider X = "aa", Y = "a". Condition holds. Permutations of X only "aa". Y is substring, YES.
Consider X = "ab", Y = "aa". Frequencies: a in Y=2, a in X=1 => fails, NO.
Thus condition seems sufficient and necessary.
But is there any scenario where Y's frequencies are a subset of X's frequencies but Y cannot be a contiguous substring of any permutation? Suppose we have X with characters that must be interleaved? For Y to be contiguous, we need to group the characters of Y together. Since we can reorder arbitrarily, we can always group them. Example: X="abc", Y="ac". Frequencies: a:1,c:1 <= X: a:1,b:1,c:1 => condition holds. Can we form permutation containing "ac" as substring? Yes: "acb" or "bac" or "bca"? "acb" contains "ac", yes. So possible.
But is there any case where Y's characters are all present in X, but because the remaining characters may need to be placed, but the total length is L, and we need to place Y as substring. We can always construct: take any ordering of remaining characters (R = X \ Y) and then insert Y somewhere. That yields a permutation. So yes.
Wait: The condition "Y is a substring of some permutation of X" is equivalent to Y being a subsequence (not necessarily contiguous) of some permutation? No.
But given we can reorder X arbitrarily, the only restriction is that we have exactly the multiset of characters X, and we need to form a string where Y appears contiguously. This is always possible if we have enough of each character to form Y. Indeed, we can just place Y at the beginning, then append the remaining characters in any order. That yields a string that is a permutation of X? Check: The string we constructed uses all characters exactly once because we used all characters from X: the Y part uses some subset, and the suffix uses the rest. So it's a valid permutation. Therefore the condition is sufficient.
Thus problem reduces to checking if for each character from 'a' to 'z', freqY[ch] <= freqX[ch].
But wait, there's a nuance: The strings A and B are given as separate, but we concatenate them directly. So X = A + B.
Also children names Ci are concatenated in order to form Y.
So we just need to compute total character counts.
But is there any twist? The example 1: X = "tommarvoloriddle", Y = "lordvoldemort". Let's verify counts: X: t:? Actually "tommarvoloriddle": let's count: t:1? 'tommarvoloriddle' has letters: t, o, m, m, a, r, v, o, l, o, r, i, d, d, l, e? Wait, need exact: "tom" + "marvoloriddle" = "tommarvoloriddle"? Actually careful: Input: "tom marvoloriddle" meaning A = "tom", B = "marvoloriddle". So X = "tom" + "marvoloriddle" = "tommarvoloriddle". Let's count characters: t: from "tom" gives t, also B maybe? B is "marvoloriddle": contains t? no. So total t:1? Actually "tom" has 't','o','m'. B = "marvoloriddle": m,a,r,v,o,l,o,r,i,d,d,l,e. So overall: characters: t:1, o: from "tom":1, from B: 'o' appears twice? B: "marvoloriddle": let's spell: m a r v o l o r i d d l e. So o appears twice? Actually positions: after v -> o, then later o before r? Actually "volo"? Let's break: m a r v o l o r i d d l e. So there are two o's? At positions: after v: o, then after l: o? Actually "volo": v-o-l-o, so yes two o's. Also from "tom": o:1, so total o: 3? Wait "tom" has o:1, so total o = 1+2=3. m: from "tom":1, from B: first character 'm'? B starts with m, so m:1 from B? Actually B = "marvoloriddle" first char m, also maybe other m? Only one m. So total m:2. a: from B:1, so a:1. r: from B: appears? B: m a r v o l o r i d d l e -> r appears twice? positions: after a: r, and after o: r? Actually "marvoloriddle": let's index: m(1) a(2) r(3) v(4) o(5) l(6) o(7) r(8) i(9) d(10) d(11) l(12) e(13). So r appears at positions 3 and 8 => 2 r's. So r:2. v:1, l: from B: positions 6 and 12 => 2 l's? Actually l appears at pos6 and pos12 => 2 l's. Also from Y? Not needed. i:1, d: positions 10 and 11 => 2 d's, e:1. Also maybe other letters? No. So X counts: t:1, o:3, m:2, a:1, r:2, v:1, l:2, i:1, d:2, e:1. Sum = 1+3+2+1+2+1+2+1+2+1 = 16? Actually length: "tom" = 3, "marvoloriddle" = 13, total 16. Good.
Now Y = "lordvoldemort": length? "lord" (4) + "voldemort" (9?) Actually "voldemort" is 9 letters? v o l d e m o r t = 9? Actually count: v(1) o(2) l(3) d(4) e(5) m(6) o(7) r(8) t(9) = 9. So total length 4+9=13. So Y = "lordvoldemort". Count letters: l:? "lord": l,o,r,d -> l:1, o:1, r:1, d:1. "voldemort": v,o,l,d,e,m,o,r,t -> v:1, o:2, l:1, d:1, e:1, m:1, r:1, t:1. So totals: l:1+1=2, o:1+2=3, r:1+1=2, d:1+1=2, v:1, e:1, m:1, t:1. Also maybe others? None. Compare to X: t:1 (X) vs Y:1 -> ok; o:3 vs 3; m:2 vs 1 -> ok; a:1 vs 0 -> ok; r:2 vs 2; v:1 vs 1; l:2 vs 2; i:1 vs 0; d:2 vs 2; e:1 vs 1. So condition holds, YES.
Example 2: X = "cheapup", Y = "heapcup". Count X: c:? cheapup = c h e a p u p: c:1, h:1, e:1, a:1, p:2, u:1? Actually "up" has u and p, so p:2, u:1. Y: heapcup = h e a p c u p? Actually "heapcup": h e a p c u p? Let's spell: h e a p c u p? That's 7 letters? "heap" = h,e,a,p; "cup" = c,u,p -> concatenated: h e a p c u p => letters: h:1, e:1, a:1, p:2? Actually p appears in "heap" and in "cup"? "cup" ends with p, so p:2, c:1, u:1. So Y counts: h:1,e:1,a:1,p:2,c:1,u:1. X: c:1,h:1,e:1,a:1,p:2,u:1. So exactly same multiset? X has also? Actually X has same letters: c:1, h:1, e:1, a:1, p:2, u:1. Yes identical. So condition holds.
Example 3: X = "brucewayne", Y = "batman". Count X: b:? "bruce" b,r,u,c,e; "wayne" w,a,y,n,e => b:1, r:1, u:1, c:1, e:2? Actually e appears in "bruce" and "wayne" => e:2, w:1, a:1, y:1, n:1. Y: b:1, a:2? "batman": b,a,t,m,a,n? Actually "batman": b a t m a n -> b:1, a:2, t:1, m:1, n:1. So Y requires t and m which are not in X, also a:2 > a:1. So condition fails, NO.
So the condition matches examples.
But wait: The problem statement says: "C should be a substring of one of the permutations of A + B." So indeed, we just check multiset subset. So why would the problem be more complicated? Possibly there is a catch: The combined lengths of children strings not exceed combined lengths of parents, so we don't need to worry about Y being longer. But also perhaps there is additional condition that the substring must be contiguous in some permutation, but if Y's frequencies <= X's frequencies, we can always construct as described. So solution seems trivial: just count frequencies.
But wait: The sample input includes "tom marvoloriddle" (A and B separated by space) and then N=2, children names: "lord" and "voldemort". The concatenated Y is "lordvoldemort". And we say condition holds. So that works.
But what about the condition "C should be a substring of one of the permutations of A + B." If Y is a substring, does it need to be exactly the concatenation? Yes. So condition is exactly as we analyzed.
But let's double-check: Suppose X = "ab", Y = "ba". Then freqY = b:1,a:1, freqX = a:1,b:1 => condition holds. Permutation of X: either "ab" or "ba". Y = "ba" is substring of "ba" (yes). So OK.
Suppose X = "aab", Y = "aba". freqY: a:2, b:1; freqX: a:2, b:1 => holds. Can we find a permutation containing "aba"? Permutations of X: aab, aba, baa. "aba" is itself a permutation, and contains "aba" as substring (whole string). So yes.
Suppose X = "abc", Y = "ab". Holds.
Suppose X = "abc", Y = "acb". freqY: a:1,c:1,b:1 => holds. Is there a permutation containing "acb"? Permutations: abc, acb, bac, bca, cab, cba. "acb" appears as a whole permutation, yes.
Suppose X = "aabc", Y = "aba". freqY: a:2,b:1; freqX: a:2,b:1,c:1 => holds. We need a permutation containing "aba". Permutations? Could we have something like "aabac"? Not exactly; we need length 4. Actually X length = 4, Y length = 3. So permutations of X of length 4. Can we find a length-4 string that contains "aba"? Let's try: "abac"? That would be a,b,a,c -> contains "aba" at positions 1-3. "abac" is a permutation? Uses a:2,b:1,c:1 -> yes "abac". So works.
Thus seems always possible.
But what about a scenario where Y uses some characters that are in X but perhaps the ordering constraints due to the rest? For example, suppose X = "ab", Y = "ab". Works. Suppose X = "aa", Y = "a". Works.
Thus the problem reduces to frequency check.
Wait, but is there any scenario where Y's frequencies are <= X's frequencies but Y cannot be a substring of any permutation because of the need to place Y contiguously while using all characters exactly once might force the remaining characters to be interleaved? But as argued, we can always place all remaining characters either entirely before Y or entirely after Y. That yields a valid permutation (since we use all characters exactly once). The only potential issue: Could the remaining characters be arranged in such a way that the string is not a permutation because we might have to use the characters in some order but that's fine. There is no restriction on order for the prefix/suffix.
Thus the condition is sufficient.
However, why would the problem be given with constraints up to 40000 per string and N up to 1000, with total children lengths <= parents lengths? If the solution is just counting frequencies, it's very simple O(total length) per test case. That would be trivial. But maybe there is a twist: They said "C should be a substring of one of the permutations of A + B." That might be misinterpreted: Actually "one of the permutations of A + B" could mean we consider all permutations of the concatenated string (i.e., we treat A+B as a multiset of characters, and we consider all possible strings formed by arranging those characters). Then C must be a substring of at least one such permutation. That is what we used.
But what if they mean that we consider all permutations of the parents' names? No, they said "one of the permutations of A + B". So we are good.
But perhaps there is an additional nuance: The concatenation of children names (C) is a string that might be very long. The combined length of children names does not exceed combined length of parents. So we have enough characters. The frequency check is necessary and sufficient. So solution is straightforward.
But let's re-read the problem statement carefully: "If N children, with names C1, C2, ..., CN, are born to parents with names A and B, and you consider C to be the concatenation of all the names of the children, i.e. C = C1 + C2 + ... + CN (where + is concatenation operator), then C should be a substring of one of the permutations of A + B." So that's exactly what we think.
Thus solution: For each test case, read A and B, compute total frequencies of X = A+B. Then read N and all Ci, concatenate them into Y (or just accumulate frequencies). Then check if for each character 'a' to 'z', freqY[ch] <= freqX[ch]. If yes, print "YES", else "NO".
Complexities: O(total length of strings) per test case, fine.
But wait: The example 1: They considered Z = "iamlordvoldemort". That's a permutation of "tommarvoloriddle"? Actually "iamlordvoldemort" is 14? Let's count: i a m l o r d v o l d e m o r t -> 16? Actually "iamlordvoldemort" length? Let's count: i (1) a (2) m (3) l (4) o (5) r (6) d (7) v (8) o (9) l (10) d (11) e (12) m (13) o (14) r (15) t (16) = 16. And "tommarvoloriddle" also 16. Are they permutations? Let's compare counts: "iamlordvoldemort": i:1, a:1, m:2? Actually letters: i,a,m,l,o,r,d,v,o,l,d,e,m,o,r,t. So counts: i:1, a:1, m:2, l:2, o:3, r:2, d:2, v:1, e:1, t:1. Compare to X counts we computed earlier: t:1, o:3, m:2, a:1, r:2, v:1, l:2, i:1, d:2, e:1. Yes same. So indeed Y is substring of that permutation. So our condition holds.
Thus problem solved.
But before finalizing, I'll check if there is any hidden nuance: Perhaps they require that C (concatenated children names) is a substring of any permutation? Or "one of the permutations" means we can choose one permutation. So it's existence.
Thus simple.
However, I recall a known problem from CodeChef or similar named "Archer's Plan" maybe? Possibly there is a catch: The concatenation of children names C must be a substring of some permutation of A+B. The trivial condition is that the multiset of characters of C is a subset of the multiset of characters of A+B. But is that always sufficient? Let's try to think of a counterexample.
Consider X has characters: 'a', 'b', 'c' with frequencies: a=2, b=1, c=1 (total 4). Y = "aba". freqY: a=2, b=1 => subset (c not used). Then can we form a permutation of X that contains "aba"? Let's attempt to construct: We need a string of length 4 that has "aba" as a contiguous substring. Possibilities: if we put Y as prefix: "aba" + remaining char (c) = "abac". Is "abac" a permutation of X? Check counts: a:2, b:1, c:1 => yes. Does "abac" contain "aba"? Yes, positions 1-3. So works.
Consider X: a=2, b=2, Y="abba". freqY: a=2, b=2 => matches exactly. Permutations containing "abba"? Could we have "abba" + nothing? That's length 4, exactly X? Actually X length = 4? Wait X: a=2,b=2 => length 4, Y length=4, so Y must be the whole permutation. So we need to see if "abba" is a permutation of X? "abba" counts a=2,b=2 => yes, it is a permutation. So Y is substring (the whole string). So OK.
Consider X: a=3, b=1, Y="aba". freqY: a=2,b=1 => subset. X length = 4, Y length = 3. Construct: prefix + Y + suffix? Let's try to construct: put Y at beginning: "aba" + remaining char (a) => "abaa". Count: a=3,b=1 => yes. Contains "aba" at positions 1-3. So works.
What about more complex scenario: X: a=1, b=1, c=1, d=1 (total 4). Y = "abac". freqY: a=2,b=1,c=1 => but X only has a=1, so fails. So not relevant.
Thus seems always possible.
One nuance: The permutation must use all characters exactly once, so when we construct a string with Y as substring and the rest as prefix/suffix, we must ensure that the resulting string is indeed a permutation of X (i.e., uses each character exactly once). That is satisfied if we take all characters of X, partition into Y-multiset and R-multiset, then order them accordingly. There is no restriction that the prefix and suffix cannot be empty; it's fine.
Thus condition is necessary and sufficient.
Therefore solution is just frequency count.
But wait, the problem statement says: "The combined lengths of all names of children will not exceed the combined length of the names of their parents." That ensures that we never have a case where Y is longer than X, which would automatically fail anyway. So we don't need to check length, but it's consistent.
Thus solution is trivial: For each test case, compute frequency array for X, for Y, and compare.
But careful: The input strings could be up to 40000 each, and there could be up to 1000 children, but the total length of children strings is at most length of X. So total input size per test case could be up to around 2 * 40000? Actually A and B each up to 40000, so X up to 80000? But combined length of children not exceed that, so total input per test case up to maybe 160k? Times T up to 100 gives up to 16 million characters, which is okay.
We'll implement efficiently: read strings, count frequencies via simple loops.
One nuance: The input format: First line T. Then for each test case: a line containing two space-separated strings A and B. The strings contain only lowercase letters, but they might be long, and there is a space between them. So we read the line, split into two strings. Could also read using input().split() which splits by whitespace. That works.
Then next line integer N. Then N lines each containing Ci.
We need to be careful that reading large input may be slow in Python; use sys.stdin.read() to parse all at once. But T up to 100, total strings length up to maybe 8 million? Actually worst-case: each test case: A and B each 40000 => 80k; children total up to 80k; so per test case ~160k; times 100 => 16M. That's fine for Python with normal input reading line by line, but might be borderline if using slow I/O. Use sys.stdin.readline for speed.
We'll implement using sys.stdin.buffer for fast reading.
But note: The children names are given each on its own line, and they can be up to 40000 length each, but total sum limited. So reading line by line is okay.
Edge cases: N=0? Not possible, N>=1 per constraints? Actually N≥1? It says 1 ≤ N ≤ 1000, so at least one child.
But what about empty strings? Length at least 1, so no empty.
So the algorithm:
For each test case:
read A and B from line (split)
freq_parent = [0]*26
for ch in A: freq_parent[ord(ch)-97] += 1
for ch in B: similarly
read N (int)
freq_child = [0]*26
total_child_len = 0
for i in range(N):
Ci = read line, strip newline (but careful: strings may contain spaces? They contain only lowercase letters, so no spaces. So .strip() is fine.)
for ch in Ci: freq_child[ord(ch)-97] += 1
then check all i: freq_child[i] <= freq_parent[i]; if all true, print YES else NO.
But wait: Should we also consider the ordering? No.
Thus done.
But hold on: I recall a known problem "Archer's Plan" from some contest? Possibly it's from CodeChef (CHN15A?). Actually there's a CodeChef problem "ARCHER" maybe. Let me think: Actually there is a CodeChef problem named "ARCHERY" but not sure. Anyway, the solution might be exactly as above.
But before finalizing, I want to be absolutely sure there is no hidden catch. Could there be a scenario where Y's frequencies are a subset, but Y cannot be a substring of any permutation because the permutation must contain Y as a contiguous block, and the surrounding characters might force that the block is split? However, we control the permutation, we can arrange them arbitrarily. So we can always put Y as a block. But suppose Y uses characters that, if placed together, would cause the rest of the characters to be placed in a way that violates the condition that the whole string is a permutation? No.
Let's try to think if there is any dependency: What if Y is exactly the same length as X? Then Y must be the entire permutation. So Y must be a permutation of X. That requires freqY == freqX. Our condition freqY <= freqX and total lengths equal implies freqY == freqX. So it's consistent.
What if Y is shorter but contains some characters that appear in X but maybe due to some combinatorial constraint of ordering, we cannot have Y as substring because the remaining characters must be placed on both sides and that might force Y to be split? But we can place all remaining characters on one side only. So that's fine.
Thus condition is sufficient.
Now, is there any scenario where the concatenation of children names is something like "ab" and X is "ba"? Actually X length 2, Y length 2, freqY==freqX => Y is permutation, so okay.
Alright.
But wait: The problem's wording: "C should be a substring of one of the permutations of A + B." Usually, "substring" means contiguous sequence of characters. So our interpretation is correct.
But I'm thinking: Could there be a trick regarding the fact that children names are concatenated, but we are not allowed to rearrange the order of children names? That is given. So Y is fixed order of characters. That order matters. For Y to be a substring of a permutation, the characters in Y must appear consecutively in that exact order. So it's not enough that the multiset of Y is a subset; the specific sequence must appear. However, the permutation is a reordering of X's characters. So the order of characters in Y is fixed; we need to find if we can pick characters from X to form Y in that order while also using the remaining characters arbitrarily. That's more restrictive than just multiset subset! Because even if we have the right counts, the order of Y might not be achievable if the characters we need to place for Y appear in a particular sequence that we might not be able to produce given that we can reorder X arbitrarily. But we can reorder X arbitrarily, so we can produce any sequence that uses characters with appropriate counts. As long as we have enough of each character, we can produce any specific string Y (since we can arrange the characters in any order). Indeed, given a multiset of characters, we can arrange them in any order; there is no restriction on the ordering. So if we have the required multiset for Y, we can place Y as a block. So the order is not a problem because we can decide the order of characters in the permutation; we just need to make sure that the block Y appears exactly. So we can set the block to be exactly Y. So again, it's sufficient.
But there is a nuance: The permutation must include all characters of X exactly once. So the block Y will use some of the characters of X. The remaining characters will be placed elsewhere. That does not affect the ability to form Y as a block, because we can simply write Y and then add the rest. So the order of Y is exactly as we want.
Thus condition holds.
Wait, but there's a subtlety: When we construct the permutation, we have to use each character exactly once. If we place Y as a block, we need to ensure that the characters we use for Y are exactly the ones we have in the multiset; but we are free to select which specific characters from X to use for Y, as long as we have the required counts. Since all characters are identical except for type, we can just pick any characters of each type. So it's fine.
Thus it's indeed a simple multiset containment check.
Thus answer is straightforward.
But why would the problem be presented with a story and example like "iamlordvoldemort"? It seems too trivial. Could there be a twist about permutations of A + B meaning we consider all permutations of the strings A and B (like as whole strings) rather than characters? For instance, "one of the permutations of A+B" could be interpreted as: we take the concatenated string A+B, and then we consider all permutations of this string (i.e., all ways to rearrange its characters). That's what we assumed. So it's correct.
I will double-check: Sometimes problems say "subsequence" not substring. But here it's substring.
Alright.
Now, I should consider the possibility that the problem expects something else: Maybe they want to check if there exists a permutation such that C is a substring, but maybe there is a constraint that the permutation must be such that the order of parents' names is preserved? No, they said "permutations of A + B", which is typical for character permutations.
But wait: Could it mean permutations of the concatenation of A and B as strings, i.e., we treat A and B as atomic entities and consider the two possible concatenations: AB or BA? That would be permutations of the two strings. However, they said "one of the permutations of A + B". If they meant permutations of the two names, they might say "one of the permutations of A and B". But they wrote "A + B", which could be interpreted as the concatenated string. The example: In case 2, X = "cheapup", which is directly A="cheap", B="up"? Actually input "cheap up". So A="cheap", B="up". A+B = "cheapup". They then say: "Since Y in itself is a permutation of X, and as every string is a substring of itself, Y is a substring of X and also a permutation of X." That suggests they treat X as the concatenated string. And they call Y a permutation of X because they have same characters. That matches our interpretation.
Thus fine.
But I recall a known problem from CodeChef: "ARCHERS" or something, where the solution is to check if the frequency of each character in the children names is less than or equal to that in parents' names. That's a very simple problem. But I'd like to double-check constraints: They said "The combined lengths of all names of children will not exceed the combined length of the names of their parents." That is used to ensure that we don't have to check length explicitly, but also maybe for some other nuance. But it's consistent.
Thus I'll go ahead with this solution.
However, before finalizing, let's think of a possible tricky case: Suppose X = "ab", Y = "aa". Fails because counts. Suppose X = "aab", Y = "aba". Works. Suppose X = "aabc", Y = "abac". Counts: Y: a:2, b:1, c:1; X: a:2, b:1, c:1 -> works. But can we have a permutation with "abac" as substring? Since length equal? Actually X length 4, Y length 4, so Y must be the whole permutation. So we need a permutation equal to "abac". Is "abac" a permutation of X? Yes, because it uses a:2,b:1,c:1. So Y is a permutation, so substring holds. So fine.
Now consider a scenario where Y has a character that appears more times than X, obviously fails.
Thus algorithm is solid.
But there might be a memory/time issue if we read and process large strings naively: we can just compute frequencies by iterating characters. That's O(L) per test case.
Implementation details:
We'll use sys.stdin.buffer.read().split()? That may be efficient but we need to handle lines: The children names are separate lines, but splitting on whitespace will also split them properly because each name is a word (no spaces). So we can read all tokens via split. However, we must be careful: The first line T, then for each test case: two strings A and B, then integer N, then N strings for children names. So all tokens are whitespace-separated. So we can simply read all tokens as list of strings from the input file using sys.stdin.read().split(). Then parse sequentially.
But there is a catch: N can be up to 1000, and each child name can be up to 40000, but splitting the entire input into tokens will store all these strings in memory, which could be large but within limits: total input maybe up to 16 million characters, plus overhead of Python strings; but that's okay for typical contest memory (256 MB). Each token stored as separate string; the total number of tokens = 2 + 1 + N per test case, sum <= T*(2+1+1000) ~ 100*1003 = 100300 tokens, which is fine. The total characters in tokens is the sum of lengths of all strings, which is ~16 million. That's okay.
But using .read().split() will load the entire input as a single string, which might be memory heavy but still okay (16 MB). In Python, 16 million characters ~ 16 MB, plus list overhead, maybe 50 MB, still okay. So we can do that for simplicity.
Alternative: Use sys.stdin.buffer.readline in a loop to avoid storing all tokens. But either is fine.
I'll implement with reading lines because it's clearer: For each test case, read a line for A and B, split into two strings. Then read a line for N, convert to int. Then for i in range(N), read line and strip newline. But we need to be careful that child name strings may be empty? No, length at least 1. Also there could be leading/trailing spaces? No.
But using sys.stdin.buffer.readline will return bytes, so we need to decode? We can keep as bytes and count frequencies using ord of each byte? Since only lowercase ascii, we can treat bytes directly: for ch in line.strip(): freq[ch-97]++ if ch is int? Actually when iterating over bytes, we get ints 0-255. So we can do: for b in line.strip(): freq[b-97] += 1. That's efficient.
But for simplicity, use sys.stdin.read().split() and parse tokens. However, .split() on the whole input splits by any whitespace, which includes newline. That's fine. But we need to know when to stop: we read T, then for each test case: read A, B, read N, then read N children strings. All are tokens.
Implementation:
import sys
def main():
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
a = next(it)
b = next(it)
n = int(next(it))
# compute freq_parent
freqP = [0]*26
for ch in a:
freqP[ord(ch)-97] += 1
for ch in b:
freqP[ord(ch)-97] += 1
freqC = [0]*26
for i in range(n):
c = next(it)
for ch in c:
freqC[ord(ch)-97] += 1
# check
ok = all(freqC[i] <= freqP[i] for i in range(26))
out_lines.append("YES" if ok else "NO")
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
That should work.
But wait: The input lines might have spaces only between A and B, but what if A or B themselves could be empty? They have length >=1, so not empty.
But consider: Could there be any stray spaces? Not.
Thus solution.
But hold on, is there any scenario where Y's characters are subset but still cannot be a substring because the permutation must be of A+B, but A and B are separate strings that we concatenate, but perhaps the permutation is of the two strings as whole, meaning we can only rearrange the order of the two strings (i.e., either AB or BA) and not the characters within them? That would be a completely different problem. Let's examine example 1: A="tom", B="marvoloriddle". If permutation only of the two strings, we have only two possible strings: "tommarvoloriddle" and "marvoloriddletom". Y = "lordvoldemort". Is Y a substring of either? "lordvoldemort" is not a substring of "tommarvoloriddle"? Let's check: "tommarvoloriddle" contains "lord"? Possibly? Actually "tommarvoloriddle" contains "lord"? Let's search: "marvoloriddle" part: ... Actually "marvoloriddle" contains "lord"? The substring "lord" appears? "marvoloriddle" has "lord"? The letters: m a r v o l o r i d d l e. There's "lor" but not "lord". So not substring. The other permutation "marvoloriddletom" also probably doesn't contain "lordvoldemort". So answer would be NO, but expected YES. So that interpretation is wrong. Also example 2: A="cheap", B="up", permutations: "cheapup" and "upcheap". Y="heapcup" is not substring of "cheapup"? "cheapup" contains "heapcup"? Check: "cheapup" -> 'heap'? Actually "cheapup" has substring "heap"? No. So that would be NO but expected YES. So definitely permutation refers to character permutation.
Thus our interpretation is correct.
Now, is there any scenario where the frequency condition is necessary but not sufficient due to the ordering constraint of Y being fixed and we need to embed Y into the permutation, but the permutation must contain all characters, and the block Y might be split if we need to interleave because the remaining characters might have to be placed such that they separate Y? But we can always avoid that by placing them all on one side. That yields a string that is a permutation: all remaining characters in any order, then Y, or Y then remaining characters. That's valid. So it's sufficient.
But wait: Is there any condition that the permutation of A+B must be such that the order of characters within A and B individually is preserved? No, permutation means any arrangement.
Thus done.
Given the simplicity, maybe the problem originally had a twist: They might ask to check if Y is a subsequence of some permutation? But no.
Alternatively, the problem might be to check if Y is a substring of some permutation of the parents' names (where parents names are considered as strings and we can permute them and also perhaps permute the characters within them? But the example clarifies.
Thus solution is as above.
But there might be an edge case: N could be large, but sum of lengths of children <= length of parents. That condition ensures that the frequency check is not trivial because if Y were longer than X, it would automatically fail; but we could check that as well.
So the answer is just frequency compare.
I'll provide final solution.
But before finalizing, I will test with some custom cases:
Case:
Input:
1
ab cd
1
acdb
We have A="ab", B="cd". X = "abcd". Y = "acdb". freqX: a1,b1,c1,d1. freqY: a1,c1,d1,b1 => same. So condition holds. Is there a permutation containing "acdb"? Permutation "acdb" itself is a permutation, so substring of itself => YES.
Case:
1
ab a
2
ba
a
Here A="ab", B="a" => X="aba" length 3. Y = "ba"+"a" = "baa"? Actually children: C1="ba", C2="a" => Y="baa". length 3. freqX: a:2? Actually "aba": a:2, b:1. freqY: "baa": a:2, b:1. So condition holds. Permutation? Need a permutation of X that contains "baa" as substring. Since length equal, need permutation = "baa". Is "baa" a permutation of X? Yes, a:2,b:1. So works.
Case:
1
a b
1
ab
X="ab", Y="ab". Condition holds. Permutations: "ab" and "ba". "ab" contains "ab", YES.
Case:
1
a b
1
ba
Y="ba", freq same, permutation "ba" exists, YES.
Case:
1
a b
1
aa
freq fails, NO.
Now think about huge strings: just counting fine.
Thus answer.
One more nuance: The input constraint says: "The lengths of all the strings including A, B, and all Ci will be in the range [1, 40000], both inclusive." So each string at least 1.
Thus code works.
Therefore final answer: implement as described.
But I suspect that the problem may actually be more complex: maybe the permutation is of the parents' names as strings (i.e., we can only rearrange the order of the parents' names, not the characters within them), and the substring must be contiguous across the concatenation of the permuted parent strings. That wouldn't match examples. So ignore.
Thus solution is trivial.
Wait, why would they give example with "iamlordvoldemort"? That seems to indicate that they are rearranging characters to form that phrase. So indeed.
Hence final solution.
Now, for completeness, I'll provide explanation: condition reduces to checking if multiset of characters in children's concatenated names is subset of that of parents' concatenated names.
Thus code.
Potential pitfalls:
When using .read().split(), it's important that no extra whitespace at the end, but that's fine.
Be careful to convert N to int after reading token.
Use ord(ch) - 97 for index.
Edge: T up to 100, and overall characters maybe up to 16 million, which is fine.
Double-check time complexity: O(total characters). Should be fine.
Thus final answer.
But I'd like to double-check constraints: The combined lengths of children names <= combined length of parents. So if we only check frequencies, we also need to ensure that total length of Y is not larger than X? Actually if frequencies condition holds, it automatically implies |Y| <= |X| because sum of frequencies is length. If freqY <= freqX component-wise, then sum(freqY) <= sum(freqX). So it's automatically satisfied. So no extra check needed.
Alright.
Thus final solution.
But maybe there is a twist: What about characters not in 'a'-'z'? They said only lowercase English letters, so fine.
Now, I'll produce final answer. ```python
import sys
def solve() -> None:
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
a = next(it)
b = next(it)
n = int(next(it))
code
# frequency of parent string A+B
parent = [0] * 26
for ch in a:
parent[ord(ch) - 97] += 1
for ch in b:
parent[ord(ch) - 97] += 1
# frequency of concatenated children names
child = [0] * 26
for _ in range(n):
c = next(it)
for ch in c:
child[ord(ch) - 97] += 1
# check if child multiset is contained in parent multiset
ok = all(child[i] <= parent[i] for i in range(26))
out.append("YES" if ok else "NO")
sys.stdout.write("\n".join(out))