Complete the multiplication grid
Time limit3sMemory limit256 MB
Count pairs of multiplicand and multiplier whose partial products and final product use only the allowed nonzero digits with the given lengths.
- Level
Medium4 of 10
- Topics
- Brute force, Math, Implementation
- Solved
- No attempts yet
Problem
* * *
× * *
-------
* * *
* * *
-------
* * * *
Replace every star in a long multiplication like the one above with one digit so that the arithmetic is correct. The digits you may write are fixed in advance, the same digit may be written many times, and you do not have to use every given digit. The digit 0 is never available.
The grid has lines. Line 1 holds the multiplicand and line 2 holds the multiplier. Lines 3 through hold the partial products, and the -th partial product from the top is the multiplicand times the -th digit of the multiplier counted from the right. Line holds the product of the two numbers. The number written on line must have exactly digits, and every one of its digits must be an allowed digit.
When the star counts are 3, 2, 3, 3, 4 with allowed digits 2, 3, 4, 6, 8, and when the star counts are 3, 3, 3, 3, 3, 5 with allowed digits 1, 2, 3, 4, 5, 9, the completed grids look like this.
2 2 2 1 1 1
× 2 2 × 1 1 1
------- ---------
4 4 4 1 1 1
4 4 4 1 1 1
------- 1 1 1
4 8 8 4 ---------
1 2 3 2 1
Input
The first line has the number of lines in the grid. The second line has the star counts separated by spaces. The third line has the count of allowed digits. The fourth line has the allowed digits separated by spaces, each one of 1 through 9 and all different.
The grid is always given in a valid shape, which means . Also and .
Output
Print on one line how many ways the grid can be completed correctly with the given digits. Two ways count as different when the multiplicand or the multiplier differs.