Ambiguous Result
InterviewTime limit1sMemory limit128 MB
Given a parenthesis-free expression of numbers joined by + and *, restore parentheses to find the smallest and largest values it can evaluate to.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Intervals, Math, Implementation
- Solved
- No attempts yet
Problem
The ACM (Advanced Cosmos Monitor) recorded a set of messages transmitted by an alien race of Space Invaders. Unfortunately, the antenna used for recording only handles the lower frequencies that represent numbers and two arithmetic operators in the space-invader language, while all parentheses (which correspond to a high frequency) were lost.
Because numbers matter to these 8-bit creatures, we need to know the range of values each message could represent. Given such a parenthesis-free expression, write a program that determines the smallest and largest values it can evaluate to once parentheses are restored.
Input
The input contains several valid arithmetic expressions, one per line. Each expression consists only of non-negative integers () and the binary operators + and *. An expression starts with a number, then numbers and operators alternate, and it ends with a number. Each expression contains numbers () and operators. There are no parentheses, no other operators, and no unary operators.
The last expression is followed by a line containing the single word END.
Output
For each input line (excluding the final END), print one line with the minimum and maximum values, separated by a single space, that can be obtained by inserting parentheses so the expression stays valid and then evaluating it.
For example, 2+1*0 can be grouped as (2+1)*0, whose value 0 is the minimum, or as 2+(1*0), whose value 2 is the maximum.
It is guaranteed that, for every placement of parentheses, the value of each parenthesized sub-expression is less than . Consequently, the maximum result is between and , inclusive.