description: It is a complicated version of problem F1. The difference between them is the constraints (F1: k ≤ 2, F2: k ≤ 10).
  
  You are given an integer n. Find the minimum integer x such that x ≥ n and the number x is k-beautiful.
  
  A number is called k-beautiful if its decimal representation having no leading zeroes contains no more than k different digits. E.g. if k = 2, the numbers 3434443, 55550, 777 and 21 are k-beautiful whereas the numbers 120, 445435 and 998244353 are not.
  
  Input
  
  The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
  
  Each test case consists of one line containing two integers n and k (1 ≤ n ≤ 10^9, 1 ≤ k ≤ 10).
  
  Output
  
  For each test case output on a separate line x — the minimum k-beautiful integer such that x ≥ n.
  
  Example
  
  Input
  
  
  6
  2021 3
  177890 2
  34512 3
  724533 4
  998244353 1
  12345678 10
  
  
  Output
  
  
  2021
  181111
  34533
  724542
  999999999
  12345678
solution: #include <bits/stdc++.h>
  using namespace std;
  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
  void file_i_o();
  void solve() {
    int n, k;
    cin >> n >> k;
    string s = to_string(n);
    string check = s;
    int m = s.length();
    while (true) {
      int i = 0;
      set<char> mark;
      while (i < m) {
        mark.insert(s[i]);
        if (mark.size() > k) {
          while (s[i] == '9') i--;
          s[i]++;
          break;
        } else if (s[i] > check[i]) {
          string ans = s.substr(0, i + 1);
          if (mark.size() < k) mark.insert('0');
          for (int j = i + 1; j < m; j++) {
            ans += *mark.begin();
          }
          cout << ans << "\n";
          return;
        }
        i++;
      }
      if (i == m) {
        cout << s << "\n";
        return;
      }
    }
  }
  void solve2() {
    int n, k;
    cin >> n >> k;
    string s = to_string(n);
    int m = s.length();
    map<char, int> mark;
    set<char> keep;
    int i = 0;
    while (i < m) {
      keep.insert(s[i]);
      mark[s[i]]++;
      if (keep.size() > k) {
        cout << "i"
             << " = " << i << endl;
        while (s[i] == '9') {
          mark[s[i]]--;
          if (mark[s[i]] == 0) mark.erase(s[i]);
          i--;
        }
        mark[s[i]]--;
        if (mark[s[i]] == 0) mark.erase(s[i]);
        s[i]++;
        mark[s[i]]++;
        keep.insert(s[i]);
        if (keep.size() < k) keep.insert('0');
        string ans = s.substr(0, i + 1);
        for (int j = i + 1; j < m; j++) {
          ans += *keep.begin();
        }
        cout << ans << "\n";
        return;
      }
      i++;
    }
    cout << n << "\n";
  }
  int32_t main(int32_t argc, char const *argv[]) {
    clock_t begin = clock();
    file_i_o();
    int tt = 1;
    cin >> tt;
    while (tt--) {
      solve();
    }
    return 0;
  }
  void file_i_o() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
  }
  