This page is still under construction.

Parts of this page are still being built. What you see may change.

Complete the multiplication grid

Time limit3sMemory limit256 MB

Summary
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 NN lines. Line 1 holds the multiplicand and line 2 holds the multiplier. Lines 3 through N−1N-1 hold the partial products, and the ii-th partial product from the top is the multiplicand times the ii-th digit of the multiplier counted from the right. Line NN holds the product of the two numbers. The number written on line ii must have exactly SiS_i 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 NN in the grid. The second line has the star counts S1,S2,…,SNS_1, S_2, \dots, S_N separated by spaces. The third line has the count KK of allowed digits. The fourth line has the KK 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 N=S2+3N = S_2 + 3. Also 1≤S1≤51 \le S_1 \le 5 and 1≤S2≤31 \le S_2 \le 3.

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.

Examples2

  1. Example 1

    Input
    5
    3 2 3 3 4
    5
    2 3 4 6 8
    
    Expected output
    1
    
  2. Example 2

    Input
    6
    3 3 3 3 3 5
    6
    1 2 3 4 5 9
    
    Expected output
    77