A programmable logic array

A PLA has two planes. The AND plane makes product terms from the inputs. The OR plane adds chosen product terms to make each output. Programming a PLA means choosing which connections to keep.

What to build

Evaluate a PLA for a list of input values.

Requirements

  • A product term is a string of n characters, one for each input: 1 means the input must be 1, 0 means it must be 0, and - means the input is not used.
  • The OR plane has one line for each output: the numbers of the product terms (counting from 0) that are added for it. A line with no numbers gives an output that is always 0.
  • For each query, print the outputs as one string of bits.

Input

The first line has n (inputs), p (product terms) and k (outputs). Then p lines with the product terms. Then k lines with the OR plane. Then a line with q, and q lines each with n input bits as one string.

Output

One line for each query: the k output bits as one string.

Constraints

1 ≤ n ≤ 5, 1 ≤ p ≤ 8, 1 ≤ k ≤ 4, 1 ≤ q ≤ 16.

Example

Input:

3 3 2
1-0
01-
111
0 1
1 2
4
100
011
111
000

Output:

10
11
01
00

Why it works

Any function can be written as a sum of products, so a PLA that has the right products and the right sums can make it. Several outputs can share a product term, which saves space compared with a ROM, where every minterm needs its own word. A - in a product term means the input is not needed, which is how simplified terms are stored.

Examples

Example 1 · Input
3 3 2
1-0
01-
111
0 1
1 2
4
100
011
111
000
Expected output
10
11
01
00
Example 2 · Input
2 2 2
10
01
0 1
0
4
00
01
10
11
Expected output
00
10
11
00

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

A product pattern matches an input when every non-`-` position equals the input bit at that position.

Hint 2

An output is 1 when at least one of the product terms listed for it matches.

Hint 3

Read the product terms into a list of strings, and the OR plane into a list of lists of indexes.

Solution

Show one correct solution (try it yourself first)
n, p, k = map(int, input().split())
products = [input().strip() for _ in range(p)]
or_plane = [list(map(int, input().split())) for _ in range(k)]
q = int(input())
for _ in range(q):
    bits = input().strip()
    match = [all(c == "-" or c == b for c, b in zip(term, bits)) for term in products]
    print("".join("1" if any(match[i] for i in line) else "0" for line in or_plane))

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Memory and programmable logic →