The Next Number (Large)

Given N, find the next integer whose count of each nonzero digit matches that of N, with zeros unrestricted.

Medium6CombinatoricsGreedyMathImplementationNo attempts yetTime limit5sMemory limit512 MB

Problem

For each digit ii from 1 to 9, let DiD_i be the number of times ii occurs in the decimal representation of NN. You write out, in ascending order, every positive integer whose decimal representation contains the digit ii exactly DiD_i times for every ii from 1 to 9. The number of times the digit 0 occurs is not restricted. No number has a leading zero.

For example, if you are writing every number with two 1s and one 5, your list starts 115, 151, 511, 1015, 1051.

You are given NN, the last number you wrote. Compute the next number in the list.

Input

The first line contains an integer TT, the number of test cases. Each of the next TT lines contains a single integer NN.

Limits

  • 1T5001 \le T \le 500
  • 1N10201 \le N \le 10^{20}

Output

For each test case, print one line in the following format.

Case #X: K

XX is the test case number starting from 1, and KK is the number that follows NN in the list.