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;
  int n, k;
  int pos;
  vector<int> num;
  void init() {
    int _n = n;
    while (_n > 0) {
      num.push_back(_n % 10);
      _n /= 10;
    }
    reverse(num.begin(), num.end());
  }
  long long ans;
  int main() {
    int t;
    cin >> t;
    while (t--) {
      num.clear();
      cin >> n >> k;
      init();
      int msk = 0;
      for (int i = 0; i < (int)num.size(); i++) msk |= (1 << num[i]);
      if (__builtin_popcount(msk) <= k) {
        printf("%d\n", n);
        continue;
      }
      ans = 1e10;
      n = (int)num.size();
      for (int i = 0; i < n; i++) {
        bool flag = 0;
        int now = 0;
        for (int j = 0; j < i; j++) now |= (1 << num[j]);
        if (__builtin_popcount(now) > k) break;
        int lft = k - __builtin_popcount(now);
        long long nans = 0;
        for (int j = 0; j < i; j++) nans = nans * 10 + num[j];
        for (int j = num[i] + 1; j <= 9; j++)
          if (now & (1 << j) || lft) {
            nans = nans * 10 + j;
            if ((now & (1 << j)) == 0) {
              now |= (1 << j);
              lft--;
            }
            flag = 1;
            break;
          }
        if (!flag) continue;
        if (!lft && (now & 1) == 0) {
          for (int j = 1; j <= 9; j++)
            if (now & (1 << j)) {
              for (int l = i + 1; l < n; l++) nans = nans * 10 + j;
              break;
            }
        } else {
          for (int l = i + 1; l < n; l++) nans = nans * 10;
        }
        ans = min(ans, nans);
      }
      printf("%lld\n", ans);
    }
    return 0;
  }
  