Alphabetomials (Small)
Time limit5sMemory limit512 MB
Given a degree-4 polynomial and a dictionary, sum its value over all phrases of up to K dictionary words, modulo 10009.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Math, Combinatorics, Implementation
- Solved
- No attempts yet
Problem
Polynomials of degree 4 and polynomials of degree 5 behave very differently. The absence of a closed formula for the roots of a general degree 5 polynomial is what produced Galois theory, which has nothing to do with this problem.
Here we only consider multi-variable polynomials of degree at most 4 over 26 variables, one variable per lowercase English letter. Here is one such polynomial:
aber+aab+c
Given a string , evaluate the polynomial on it: substitute each variable with the number of times that letter appears in . The result is .
For example, take the polynomial above and let be abracadabra edgar. It has six a's, two b's, one c, one e, and three r's, so
p(S) = 6 * 2 * 1 * 3 + 6 * 6 * 2 + 1 = 109
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 every is a word of the dictionary. That is, is dictionary words joined by single spaces. The same word may be used more than once, and two phrases that place the words in a different order count as different.
You are given an integer . For every with , compute the sum of over all -phrases. The answers can be large, so print each of them modulo 10009.
Input
The first line contains the number of test cases . Each test case has this format:
- One line with the polynomial , then a space, then an integer .
- One line with the number of words in the dictionary, .
- Then lines, each with one word made of lowercase letters only. No word appears twice in the same test case.
A polynomial is always written as a sum of terms, and each term is a product of variables. A power is written as copies of a concatenated, so is written aab. The variables inside one term are always in non-decreasing alphabetical order.
Limits
- is one or more terms joined by
+. It does not start or end 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, consists of lowercase English letters only, and is at most 50 characters long.
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 number is the sum of over all -phrases, taken modulo 10009.