This page is still under construction.

Parts of this page are still being built. What you see may change.

Seconds Before the War

Time limit5sMemory limit512 MB

Summary
Given a string of letters and digits treated as a numeral in an unknown base, find the smallest value it can represent.
Level

Medium7 of 10

Topics
Greedy, Math, Implementation, Sorting
Solved
No attempts yet

Problem

In the year 2100 aliens reached Earth. They left a message written in a language nobody can read, and next to it a row of symbols. The row of symbols spells out a number, and that number is how many seconds remain before a war begins.

Nobody knows what a single symbol means. Each symbol stands for one digit, but which digit hides behind which symbol is unknown, and so is the base the aliens write in. If they wrote ab2ac999, they may have meant 31536000 in base 10, which is exactly one year, or 12314555 in base 6, which is 398951 seconds, a little over four and a half days.

Three facts are certain. The number is positive, the aliens never begin a number with a zero, and they do not write in base 1.

Find the smallest number of seconds the message can stand for.

Input

The first line has one integer TT, the number of test cases. Each of the next TT lines holds one message on a line by itself. A message uses only the characters a to z and 0 to 9, with no spaces and no punctuation. The test cases are independent, so two messages may use different bases and may give different digits to the same symbol.

  • 1≤T≤1001 \le T \le 100
  • The length of each message is at least 11 and at most 6060
  • The answer never exceeds 101810^{18}

Output

For each test case, print one line in this format:

Case #X: V

XX is the case number starting from 1, and VV is the smallest number of seconds before the war begins.

Examples4

  1. Example 1

    Input
    3
    11001001
    cats
    zig
    
    Expected output
    Case #1: 201
    Case #2: 75
    Case #3: 11
    
  2. Example 2

    Input
    3
    a
    0
    z
    
    Expected output
    Case #1: 1
    Case #2: 1
    Case #3: 1
    
  3. Example 3

    Input
    4
    ab
    ba
    abab
    aabb
    
    Expected output
    Case #1: 2
    Case #2: 2
    Case #3: 10
    Case #4: 12
    
  4. Example 4

    Input
    3
    aba
    aab
    abb
    
    Expected output
    Case #1: 5
    Case #2: 6
    Case #3: 4