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 int64_t maxn = 1e5 + 1;
  void solve() {
    int64_t n, k;
    cin >> n >> k;
    int64_t m = n;
    int64_t ans = 1;
    int64_t pw = 1;
    vector<int64_t> d, p, rp;
    set<int64_t> st;
    for (; n; n /= 10) {
      d.push_back(n % 10);
      p.push_back(pw);
      rp.push_back(ans);
      st.insert(n % 10);
      pw *= 10;
      ans += pw;
    }
    if (st.size() <= k) {
      cout << m << '\n';
      return;
    }
    st.clear();
    reverse(d.begin(), d.end());
    reverse(p.begin(), p.end());
    reverse(rp.begin(), rp.end());
    int64_t x = 0;
    for (int64_t i = 0; i < d.size(); i++) {
      for (int64_t cd = d[i] + 1; cd <= 9; cd++) {
        if (st.size() == k && !st.count(cd)) continue;
        int64_t nx = x + p[i] * cd;
        if (st.size() + (!st.count(cd)) + (!st.count(0)) > k)
          nx += (rp[i] / 10) * min(cd, st.empty() ? cd : *st.begin());
        ans = min(ans, nx);
        break;
      }
      st.insert(d[i]);
      if (st.size() > k) break;
      x += p[i] * d[i];
    }
    cout << ans << '\n';
  }
  int32_t main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int64_t t;
    cin >> t;
    while (t--) solve();
    return 0;
  }
  