Costly Binary Search (Large)

Given the cost of comparing against each array position, find the smallest worst-case total cost of an adaptive binary search for the insertion point.

Hard8Dynamic programmingDivide and conquerGreedyNo attempts yetTime limit60sMemory limit1536 MB

Problem

You want to insert one new object into a sorted array, and you find the insertion position by binary search. Comparing the new object with an object of the array answers either "greater" or "less". "Greater" means the new object goes to the right of the compared object, and "less" means it goes to the left. A comparison never answers "equal" in this problem.

The answers never contradict each other. If the new object is greater than some object of the array, it is also greater than every object to the left of that one. If it is less than some object, it is also less than every object to the right of that one. For an array of nn elements there are n+1n+1 possible insertion positions.

Comparisons do not all cost the same. Comparing the new object with the ii-th object of the array costs aia_i, an integer between 1 and 9.

You may pick the next object to compare after seeing the answers so far. Play a strategy that minimizes the total cost in the worst case, and report that worst-case total cost.

Input

The first line has the number of test cases TT. Each of the next TT lines holds the comparison costs a1,a2,,ana_1, a_2, \dots, a_n of one test case as a sequence of digits written with no spaces. The length nn of the array is the length of that sequence.

Limits

  • 1T501 \le T \le 50
  • Every digit is between 1 and 9.
  • There are no spaces between the digits on one line.
  • 1n1061 \le n \le 10^6

Output

For each test case, print one line Case #x: y, where xx is the test case number starting from 1 and yy is the worst-case total cost of the binary search.