P1812 Interval Arithmetic
Description
Interval arithmetic is a branch of mathematics. In interval arithmetic, constants and variables are not represented by a single exact value, but by an interval or range with a lower and an upper bound. In ordinary arithmetic, a quantity can be represented as a point on the number line; in interval arithmetic, a quantity is represented as a segment on the number line, for example, $[3,5]$ denotes the segment from $3$ to $5$. When an exact number is represented as an interval, the upper and lower bounds are identical, e.g., $5$ as an interval is $[5,5]$.
An operation on two intervals means applying the operation to every point in one interval with every point in the other interval; the set of all resulting points is the result of the operation. For example, $[3,5]+[-10,1]=[-7,6]$. Your task is to write a program that can perform the basic interval operations of unary negation, addition, subtraction, multiplication, and division according to a single-line expression. Here are some examples:
- Negation: $-[-3,5]=[-5,3]$.
- Addition: $[3,5]+[-10,1]=[-7,6]$.
- Subtraction: $[3,5]-[-10,1]=[2,15]$.
- Multiplication: $[3,5]\times [-10,1]=[-50,5]$.
- Division: $[3,5]\div [-10,-0.1]=[-50,-0.3]$.
Input Format
The input consists of one or more lines, each containing an infix expression over intervals. Each interval is written as $[\min,\max]$. Expressions may include parentheses, the minus sign ($\verb!-!$), plus ($\verb!+!$), minus ($\verb!-!$), multiplication ($\verb!*!$), and division ($\verb!/!$); parentheses may be nested. A line may contain spaces, but no space appears inside the brackets of an interval $[\min,\max]$ or immediately after a minus sign. Scientific notation need not be handled, e.g., $\verb!2E6!=2\times 10^6$. Each line contains at most $80$ characters. Operations follow the standard precedence rules. Operators are listed below in decreasing order of precedence:
- $\verb!(!,\verb!)!$ parentheses.
- $\verb!-!$ unary negation.
- $\verb!*!,\verb!/!$ multiplication and division; operators of the same precedence are evaluated from left to right.
- $\verb!+!,\verb!-!$ addition and subtraction; operators of the same precedence are evaluated from left to right.
Output Format
For each input line, output the result as $[\min,\max]$ (both endpoints rounded to $3$ decimal places). Print one result per line. There must be no spaces in the output. During evaluation, if an interval that contains $0$ is used as a divisor, output `Division by zero`.
Explanation/Hint
Translated by ChatGPT 5