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: import os, sys
  from io import BytesIO, IOBase
  
  
  class FastIO(IOBase):
      newlines = 0
  
      def __init__(self, file):
          self._fd = file.fileno()
          self.buffer = BytesIO()
          self.writable = "x" in file.mode or "r" not in file.mode
          self.write = self.buffer.write if self.writable else None
  
      def read(self):
          while True:
              b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))
              if not b:
                  break
              ptr = self.buffer.tell()
              self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
          self.newlines = 0
          return self.buffer.read()
  
      def readline(self):
          while self.newlines == 0:
              b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))
              self.newlines = b.count(b"\n") + (not b)
              ptr = self.buffer.tell()
              self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
          self.newlines -= 1
          return self.buffer.readline()
  
      def flush(self):
          if self.writable:
              os.write(self._fd, self.buffer.getvalue())
              self.buffer.truncate(0), self.buffer.seek(0)
  
  
  class IOWrapper(IOBase):
      def __init__(self, file):
          self.buffer = FastIO(file)
          self.flush = self.buffer.flush
          self.writable = self.buffer.writable
          self.write = lambda s: self.buffer.write(s.encode("ascii"))
          self.read = lambda: self.buffer.read().decode("ascii")
          self.readline = lambda: self.buffer.readline().decode("ascii")
  
  
  class dict(dict):
      def __missing__(self, key):
          return 0
  
  
  sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
  input = lambda: sys.stdin.readline().rstrip("\r\n")
  inp = lambda dtype: dtype(input().strip())
  inp_d = lambda dtype: [dtype(x) for x in input().split()]
  inp_2d = lambda dtype, n: [inp(dtype) for _ in range(n)]
  inp_2ds = lambda dtype, n: [inp_d(dtype) for _ in range(n)]
  inp_enu = lambda dtype: [(i, x) for i, x in enumerate(inp_d(dtype))]
  inp_enus = lambda dtype, n: [[i] + [inp_d(dtype)] for i in range(n)]
  ceil1 = lambda a, b: (a + b - 1) // b
  get_bit = lambda x, i: (x >> i) & 1
  
  for _ in range(inp(int)):
      n, k = inp_d(int)
      n1 = str(n)
      ans, ln = float('inf'), len(n1)
  
      digs = set()
      for i in n1:
          if len(digs) == k - 1:
              break
          digs.add(i)
  
      digs = list(digs)
      for i in range(10):
          cur, lst, flag = [], -1, 0
  
          if str(i) not in digs:
              digs.append(str(i))
              flag = 1
  
          digs.sort()
  
          for j in n1:
              for dig in digs[:-1]:
                  if j <= dig:
                      cur.append(dig)
                      if j < dig:
                          cur.extend([digs[0]] * (ln - len(cur)))
  
                      lst = len(cur) - 1
                      break
              else:
  
                  if j <= digs[-1]:
                      cur.append(digs[-1])
                      if j < digs[-1]:
                          cur.extend([digs[0]] * (ln - len(cur)))
                          break
  
                  elif lst == -1:
                      cur = ['9'] * 10
                      break
                  else:
                      cur = cur[:lst + 1]
                      for dig in digs:
                          if cur[lst] < dig:
                              cur[lst] = dig
                              break
  
                      cur.extend([digs[0]] * (ln - len(cur)))
                      break
  
              if len(cur) == len(n1):
                  break
  
          if flag:
              digs.remove(str(i))
          ans = min(ans, int(''.join(cur)))
  
      print(ans)
  