#C5212. Evaluate Arithmetic Expression with Variables
Evaluate Arithmetic Expression with Variables
Evaluate Arithmetic Expression with Variables
You are given an arithmetic expression in the form of a string containing integers, variable names, the operators +
and -
, and parentheses. In addition, a set of variable assignments is provided as input. Your task is to evaluate the expression after substituting each variable with its corresponding value.
The grammar of the expression can be described using the following formal definition in LaTeX:
$$\text{Expr} \to \text{Term} \;\vert\; \text{Expr} + \text{Term} \;\vert\; \text{Expr} - \text{Term} $$and
$$\text{Term} \to \text{Number} \;\vert\; (\text{Expr}) $$Note that variable names consist of alphabetic characters (and possibly digits) and will be replaced by their provided integer values. You may assume that all expressions are valid and that the variables in the expression always exist in the provided list.
inputFormat
The input is read from stdin
and has the following format:
- The first line contains the arithmetic expression as a string. The expression may contain spaces.
- The second line contains an integer N representing the number of variables.
- The following N lines each contain a variable name and its integer value separated by a space.
For example:
a + b 2 a 2 b 3
outputFormat
Output a single integer to stdout
which is the evaluated result of the expression.
For the above example, the output should be:
5## sample
a + b
2
a 2
b 3
5