This page is still under construction.

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

Serial Numbers

Time limit1sMemory limit128 MB

Summary
Given up to 10 forbidden digit substrings, find the b-th smallest positive integer whose decimal form contains none of them as a substring.
Level

Medium7 of 10

Topics
Dynamic programming, String matching, Binary search, Combinatorics
Solved
No attempts yet

Problem

A factory manufactures items on assembly lines and stamps each one with a serial number so the items can be told apart. A simple multi-function counter generates these serial numbers sequentially in increasing order: 1, 2, 3, and so on.

Because the counter reuses its digit display for internal op-codes (command codes), certain digit strings are reserved and must never appear as a substring of any serial number it prints. For example, if 23 is a reserved op-code, then no serial number may contain 23 anywhere in its decimal representation. Assuming 23 is the only reserved code, the serial numbers run:

1, 2, 3, ..., 21, 22, 24, 25, ..., 121, 122, 124, 125, ..., 228, 229, 240, 241, 242, ...

(every number that contains 23, such as 23, 123, and 230-239, is skipped).

As a result, the imprinted serial number differs from the item's production batch number, which is simply the sequential count of items produced (1, 2, 3, ...). The system does not store the mapping between the two, which makes an individual item hard to trace (for a recall or inspection). Given the production batch number of an item, determine its serial number.

Equivalently: given a set of reserved op-code strings and an index bb, output the bb-th smallest positive integer whose decimal representation contains none of the reserved strings as a substring.

Input

The first line contains an integer TT (T≤100T \le 100), the number of test cases.

Each test case consists of two lines:

  • The first line contains an integer KK (1≤K≤101 \le K \le 10), the number of reserved op-codes, followed by KK op-codes. Each op-code is a string of 1 to 10 digits, and leading zeros are significant (for example, 012 and 12 are different).
  • The second line contains an integer NN (1≤N≤1001 \le N \le 100), the number of queries, followed by NN production batch numbers. Each production batch number is a positive integer.

You may assume that every requested serial number fits in a signed 32-bit integer.

Output

For each test case, print one line with the NN serial numbers corresponding to the requested production batch numbers, in order. Two adjacent integers are separated by a single space.

Examples1

  1. Example 1

    Input
    4
    1 4
    2 3 5
    1 2
    3 4 5 6
    2 4 13
    3 4 13 888
    3 012 345 6789
    2 12345 67890
    
    Expected output
    3 6
    5 6 7
    5 16 1230
    12391 68273