Costly Binary Search (Small)
Time limit5sMemory limit512 MB
Find the comparison order that minimizes the worst-case total cost of locating the insertion position when each array slot has its own comparison cost.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Tree, Binary search
- Solved
- No attempts yet
Problem
You are implementing binary search. There is a sorted array of objects and one new object that you want to insert into it. To find the insertion position you compare the new object with objects of the array. A comparison answers either greater, meaning the new object belongs to the right of the compared object, or less, meaning it belongs to the left. In this problem a comparison never answers equal. When the new object is greater than some object of the array, it is also greater than every object to the left of that object, and when it is less than some object, it is also less than every object to the right of that object. So an array of elements has possible insertion positions.
Comparisons do not all cost the same. Comparing the new object with the -th object of the array costs , an integer between 1 and 9 inclusive.
Assume you follow a strategy that minimizes the total cost in the worst case. Find that worst case total cost.
Input
The first line contains the number of test cases . Each of the next lines contains one string of digits that gives the comparison costs of one test case in order. The length of that string is the size of the array.
Constraints
- Every digit is between 1 and 9 inclusive.
- A line contains no spaces.
Output
For each test case print one line in the form Case #x: y, where is the test case number starting from 1 and is the worst case total cost of the binary search.