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. if ((int)cur.size() == len) {
  16. if (cur[0] == '0') return;
  17.  
  18. int num = stoll(cur);
  19. ans = min(ans, abs(target - num));
  20. return;
  21. }
  22.  
  23. for (int x : d) {
  24. generate(cur + char(x + '0'), len, d, target);
  25. }
  26. }
  27.  
  28. void solve() {
  29.  
  30. int a, n;
  31. cin >> a >> n;
  32.  
  33. vector<int> b(n);
  34.  
  35. for (int i = 0; i < n; i++) cin >> b[i];
  36.  
  37. int digits = to_string(a).size();
  38.  
  39. ans = INF;
  40.  
  41. generate("", digits, b, a);
  42.  
  43. if (digits > 1)
  44. generate("", digits - 1, b, a);
  45.  
  46. generate("", digits + 1, b, a);
  47.  
  48. cout << ans << endl;
  49. }
  50.  
  51. int32_t main() {
  52.  
  53. fast_io;
  54.  
  55. int t;
  56. cin >> t;
  57.  
  58. while (t--) solve();
  59.  
  60. return 0;
  61. }
Success #stdin #stdout 0s 5320KB
stdin
4
0 2
0 1
11 2
1 2
222 2
3 4
3333 2
6 7
stdout
1
0
111
2556