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;
  const int INF = (1 << 30) - 1;
  const long long LINF = (1LL << 60) - 1;
  template <class T>
  bool chmax(T &a, T b) {
    if (a < b) {
      a = b;
      return true;
    } else
      return false;
  }
  template <class T>
  bool chmin(T &a, T b) {
    if (a > b) {
      a = b;
      return true;
    } else
      return false;
  }
  int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin >> t;
    while (t--) {
      string n;
      cin >> n;
      int k;
      cin >> k;
      vector<vector<vector<long long> > > ans(
          n.size() + 1,
          vector<vector<long long> >(11, vector<long long>(2, LINF)));
      ans[0][0][0] = 0;
      for (int i = 0; i < n.size(); i++) {
        int ni = n[i] - '0';
        for (int j = 0; j < 11; j++) {
          for (int k = 0; k < 2; k++) {
            if (ans[i][j][k] == LINF) continue;
            set<int> st;
            long long m = ans[i][j][k];
            while (m) {
              st.insert(m % 10);
              m /= 10;
            }
            for (int x = (k ? 0 : ni); x < 10; x++) {
              chmin(ans[i + 1][j + (st.find(x) == st.end())][k || (x > ni)],
                    ans[i][j][k] * 10 + x);
            }
          }
        }
      }
      long long res = LINF;
      for (int l = 0; l < k + 1; l++) {
        for (int j = 0; j < 2; j++) chmin(res, ans[n.size()][l][j]);
      }
      cout << res << endl;
    }
    return 0;
  }
  