human
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
 ... What is a Python program to find the minimum integer x such that x ≥ n and the number x is k-beautiful?
assistant
#Here is Python program to find the minimum integer x such that x ≥ n and the number x is k-beautiful.

#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
vector<int> lim;
i64 dp[20][1 << 11][2][11];
i64 solve(int p, int mask, int k, int s, int tight) {
  if (p < 0) return __builtin_popcount(mask) <= k;
  i64& res = dp[p][mask][s][k];
  if (tight && ~res) return res;
  i64 cnt = 0;
  for (int i = 0; i <= (tight ? 9 : lim[p]); i++) {
    if (!s && i == 0) {
      cnt += solve(p - 1, 0, k, 0, 1);
    }
    if (!s && i == 0) continue;
    int nxt_mask = mask | (1 << i);
    cnt += solve(p - 1, nxt_mask, k, 1, tight | (i < lim[p]));
  }
  return (tight ? res = cnt : cnt);
}
i64 getSolve(i64 n, int k) {
  lim.clear();
  while (n) {
    lim.emplace_back(n % 10);
    n /= 10;
  }
  return solve((int)lim.size() - 1, 0, k, 0, 0);
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int tt;
  cin >> tt;
  memset(dp, -1, sizeof(dp));
  while (tt--) {
    int n, k;
    cin >> n >> k;
    if (getSolve(n, k) - getSolve(n - 1, k) >= 1) {
      cout << n << '\n';
      continue;
    }
    i64 def = getSolve(n, k);
    i64 lo = n + 1, hi = 1e18;
    while (lo < hi) {
      const i64 mid = lo + (hi - lo) / 2;
      if (getSolve(mid, k) > def)
        hi = mid;
      else
        lo = mid + 1;
    }
    cout << hi << '\n';
  }
  return 0;
}