Under construction

Still being built. Things may change

K-Balanced Number

Time limit3sMemory limit1024 MB

Summary
Given X and K, find the largest number not above X whose most and least used digits (unused digits excluded) differ in count by at most K.
Level

Medium7 of 10

Topics
Dynamic programming, Greedy, String
Solved
No attempts yet

Problem

A decimal number is written using only the digits 0 through 9.

For a positive integer NN, look at the digits used to write NN in decimal, where NN does not start with 0. If the count of the most frequently used digit minus the count of the least frequently used digit is at most KK, then NN is called a KK-balanced number.

Given positive integers XX and KK, find the largest KK-balanced number that is less than or equal to XX.

Input

The first line contains the number of test cases TT. (1≤T≤105)(1 \leq T \leq 10^5)

Each of the next TT lines contains positive integers XX and KK, separated by a space. (1≤X<10105,1≤K≤105)(1 \leq X < 10^{10^5}, 1 \leq K \leq 10^5)

In all test cases, the sum of the lengths of XX is at most 10510^5.

Output

For each test case, print the answer on its own line, in input order.

Hints

  • The input and output can exceed the range of a 64-bit integer.
  • Digits that are not used are not counted.
  • Python users are recommended to submit with PyPy.

Examples1

  1. Example 1

    Input
    4
    10000 1
    10000 3
    112222 1
    32334837373633003033 3
    
    Expected output
    9999
    10000
    112221
    32334837373488887422