Infix to Prefix
Time limit5sMemory limit128 MB
Given a prefix expression with spaces and parentheses removed, compute the smallest and largest values over all valid parses.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Intervals, String
- Solved
- No attempts yet
Problem
Jaap wrote a program for a lab assignment. The task was simple: convert an arithmetic expression in infix notation into an expression in Polish (prefix) notation. Infix notation puts the operator between its operands (12 + 5), while prefix notation puts the operator to the left of its operands (+ 12 5).
This is the syntax of the expression Jaap had to convert.
Expression ::= Number
| '(' Expression Op Expression ')'
| '(' '-' Expression ')'
Op ::= '+' | '-'
Number ::= Digit | Number Digit
Digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
A Number with more than one digit does not start with 0. A Number has at most 9 digits.
At this point we have to admit that the assignment was not specified very well. The syntax of the resulting expression was never given, so Jaap had to decide a few things himself, and he decided wrong.
His first mistake was believing that spaces are superfluous in prefix notation. That holds in infix notation, where an operator always sits between two numbers, but in prefix notation the numbers have to be separated from one another. Dropping every space, as Jaap did, gives rise to expressions like +1234, which has three different readings. (Exercise: draw the three different syntax trees.)
His second mistake was believing that parentheses are superfluous in prefix notation. Prefix notation without parentheses is unambiguous only when the arity of every operator is fixed. Ambiguity appears as soon as a unary minus and a binary minus are both in play. The expression --34 can be read as (- (- 3 4)), which evaluates to 1, or as (- (- 3) 4), which evaluates to -7, or even as (- (- 34)), which evaluates to 34.
We do not ask you to reconstruct Jaap's program. We ask you to work out how ambiguous his output is.
Input
The input holds several test cases. Each test case is one line with a single nonempty string of length at most 1000. The string contains only +, -, and the digits 0 through 9. The string is what Jaap's program printed, so it has at least one reading as a prefix expression with the spaces and the parentheses dropped. Process every test case until the end of the input.
Output
For each test case, print one line with two numbers: the smallest and the largest value that different readings of the input expression can produce, in that order, separated by a single space.