Serial Numbers
Time limit1sMemory limit128 MB
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 , output the -th smallest positive integer whose decimal representation contains none of the reserved strings as a substring.
Input
The first line contains an integer (), the number of test cases.
Each test case consists of two lines:
- The first line contains an integer (), the number of reserved op-codes, followed by op-codes. Each op-code is a string of 1 to 10 digits, and leading zeros are significant (for example,
012and12are different). - The second line contains an integer (), the number of queries, followed by 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 serial numbers corresponding to the requested production batch numbers, in order. Two adjacent integers are separated by a single space.