Alphabetomials (Large)
Time limit5sMemory limit512 MB
Given a polynomial over 26 letter counts and a dictionary, sum its value over all phrases of 1 to K dictionary words, modulo 10009.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Combinatorics, Math, Implementation
- Solved
- No attempts yet
Problem
We work only with multi-variable polynomials of degree at most 4 over 26 variables, one variable for each lowercase English letter. Here is one such polynomial:
aber+aab+c
Given a string , evaluate the polynomial on it. Every variable is replaced by the number of times that letter appears in , and the result is called .
For example, take the polynomial above and let be abracadabra edgar. It contains six a's, two b's, one c, one e, and three r's, so
You are given a dictionary of distinct words made of lowercase letters only. A string is a -phrase if
S = "S1 S2 S3 ... Sd"
where each is a word from the dictionary. That is, is dictionary words joined by single spaces, and the same word may be used more than once. Given with , compute the sum of over all -phrases, for every with . The sums get large, so report each one modulo 10009.
Input
The first line contains the number of test cases . Each test case has this format:
- a line with an expression for the polynomial, then one space, then an integer ;
- a line with an integer , the number of words in the dictionary;
- lines, each holding one word made of lowercase letters only. No word repeats inside one test case.
A polynomial is always written as a sum of terms, and each term is a product of variables. is written as copies of the letter a concatenated, so is written as aab. The variables inside a term are always in non-decreasing lexicographic order.
Constraints
- is one or more terms joined by
+, and it neither starts nor ends with+. Each has at most 5 terms. Each term has at least 1 and at most 4 lowercase letters in non-decreasing order. No two terms of one polynomial are equal. - Each word is non-empty, uses only lowercase English letters, and is at most 50 characters long. No word repeats inside one dictionary.
Output
For each test case, print a single line in the form
Case #X: sum1 sum2 ... sumK
where is the case number starting from 1, and the -th value is the sum of over all -phrases, taken modulo 10009.