Word Equations
Time limit1sMemory limit128 MB
Count the binary word assignments to variables of fixed lengths that make the two sides of a word equation equal.
- Level
Hard8 of 10
- Topics
- String, Union-find, Graph, Math
- Solved
- No attempts yet
Problem
Every non-empty sequence of the symbols 0 and 1 is called a binary word. A word equation has the form
where each and each is either a binary digit (0 or 1) or a variable (a lowercase letter of the English alphabet).
Every variable has a fixed length: the number of binary digits of the words that may be substituted for it. To solve a word equation you must assign to every variable a binary word of exactly that variable's length, so that after substituting the assigned words for all variables, the left side and the right side become the same binary word.
For example, let be variables of lengths respectively, and consider the equation
It has exactly distinct solutions.
For a given equation, compute how many distinct solutions it has. Your program should:
- read the number of equations and their descriptions from standard input;
- find the number of solutions of each equation;
- write the results to standard output.
Input
The first line contains an integer (), the number of equations. The descriptions of the equations follow, with no blank lines between them. Each description consists of exactly six lines:
- An integer (), the number of distinct variables in the equation. The variables are the first lowercase letters of the English alphabet.
- A sequence of positive integers separated by single spaces: the lengths of the variables in order (the first number is the length of , the second the length of , and so on). When this line is empty.
- An integer , the length of the left side of the equation, that is, the number of digits and variable letters written in it.
- The left side of the equation, written as a string of digits and variable letters with no spaces.
- An integer , the length of the right side of the equation.
- The right side of the equation, encoded in the same way as the left side.
On each side, the number of digits plus the sum of the lengths of the variables (counting every occurrence of a variable) is at most .
Output
For each from to , write on the -th line the number of distinct solutions of the -th equation.