fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define fast_io ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
  5.  
  6. #define int long long
  7. #define pb push_back
  8. #define endl '\n'
  9.  
  10. const int INF = 1e18;
  11.  
  12. int ans;
  13.  
  14. void generate(string cur, int len, vector<int>& d, int target) {
  15.  
  16. if ((int)cur.size() == len) {
  17.  
  18. if (cur.size() > 1 && cur[0] == '0')
  19. return;
  20.  
  21. int num = stoll(cur);
  22.  
  23. ans = min(ans, abs(target - num));
  24.  
  25. return;
  26. }
  27.  
  28. for (int x : d) {
  29. generate(cur + char(x + '0'), len, d, target);
  30. }
  31. }
  32.  
  33. void solve() {
  34.  
  35. int a, n;
  36. cin >> a >> n;
  37.  
  38. vector<int> b(n);
  39.  
  40. for (int i = 0; i < n; i++) cin >> b[i];
  41.  
  42. int digits = to_string(a).size();
  43.  
  44. ans = INF;
  45.  
  46. generate("", digits, b, a);
  47.  
  48. if (digits > 1)
  49. generate("", digits - 1, b, a);
  50.  
  51. generate("", digits + 1, b, a);
  52.  
  53. cout << ans << endl;
  54. }
  55.  
  56. int32_t main() {
  57.  
  58. fast_io;
  59.  
  60. int t;
  61. cin >> t;
  62.  
  63. while (t--) solve();
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 5308KB
stdin
4
0 2
0 1
11 2
1 2
222 2
3 4
3333 2
6 7
stdout
0
0
111
2556