Codeforces Round 1098 (Div. 2)
C2
Cirno and Number (Hard Version)
Codeforces
1600
原题
← C1D →
翻译中…

Led On by a Cow to Visit Zenkou Temple— Neo-traditionalism of Japan

翻译中…

This is the hard version of the problem. The difference between the versions is that in this version, $1\le n\le 10$. You can hack only if you solved all versions of this problem.

翻译中…

You are given a non-negative integer $a$ and a non-empty, strictly increasing sequence of digits $d$ of length $n$, where $0 \le d_i \le 9$.

翻译中…

Find the minimum value of $|a - b|$ over all non-negative integers $b$ whose decimal representation contains only digits from $d$.

翻译中…

Input

翻译中…

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows.

翻译中…

The first line of each test case contains two integers $a$ and $n$ ($0\le a\le 10^{17}$, $1\le n\le 10$).

翻译中…

The second line contains $n$ integers $d_1,d_2,\ldots,d_n$. It is guaranteed that $0\le d_1 \lt d_2 \lt \ldots \lt d_n\le 9$.

翻译中…

Output

翻译中…

For each test case, output the minimum value of $|a - b|$.

翻译中…

Note

翻译中…

In the first test case, $a=0$, $b=0$, and $|a - b|=0$.

翻译中…

In the second test case, $a=11$, $b=11$, and $|a - b|=0$.

翻译中…

In the third test case, $a=222$, $b=333$, and $|a - b|=111$.

翻译中…

In the fourth test case, $a=3333$, $b=999$, and $|a - b|=2334$.

翻译中…

样例

Input #1
4
0 1
0
11 2
1 2
222 3
3 4 5
3333 4
6 7 8 9
Output #1
0
0
111
2334
InputCopy OutputCopy
题目信息
题号
2228C2
时间限制
2 s
内存限制
256 MB
标签
二分
DFS 及类似
动态规划
贪心
模拟

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。