Polly Nomials
Time limit1sMemory limit128 MB
For each polynomial with leading coefficient 1, evaluate it at x = 1 or -1 and find the minimum key presses needed to compute it on a left-to-right calculator.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Math, Greedy, Implementation
- Solved
- No attempts yet
Problem
The International Ornithologists Union runs the Avian Computation Mission (ACM), which studies the computational ability of birds. In its most famous project, the "Polly Nomial" project, parrots are trained to evaluate simple polynomials in one variable with non-negative integer coefficients.
Each parrot uses a Parrot Digital Assistant (PDA), a beak-operated calculator. Its keys are the digits through , the symbol , and the operators , , and . The key stands for the variable; its numeric value is set internally for testing, but the parrot only ever sees the symbol .
The PDA works like a basic immediate-execution calculator: it has NO extra memory and NO operator precedence. It evaluates strictly left to right, applying each or immediately to the value currently on the display and the next operand that is entered. An operand is either the variable or a non-negative integer typed one digit at a time.
For example, to compute a parrot might press:
which evaluates as .
Because the PDA has no memory, the parrot cannot store a partial result. For a polynomial such as it cannot first compute and set it aside while computing ; it must instead choose an order of operations (for instance a nested, Horner-style scheme) that reaches the answer using only the single display.
The cost of a computation is the total number of key presses, including the final . For the sequence above costs : four presses of , two of , two of , two presses of the digit , and one . This happens to be the minimum possible cost for that polynomial.
Write a program that, for each given polynomial, reports its value at the given and the minimum possible key-press cost. Because parrots are intimidated by a leading coefficient other than , the highest-degree coefficient is always .
Input
Each line describes one polynomial . A line begins with the degree (), followed by the non-negative coefficients in order of decreasing power (with always), and finally the integer value of , which is always either or . The input ends with a line containing the two values 0 0, which must not be processed.
Output
For each polynomial, print a line of the form Polynomial i: value cost, where i is the polynomial's position in the input (starting from ), value is the polynomial evaluated at the given , and cost is the minimum number of key presses (including the final ) needed to compute it.