P2186 Xiao Z's Stack Function

Description

Xiao Z recently found a magical machine whose operations are all done by maintaining a stack. It supports the following 11 operations: - $\texttt{NUM} ~x$: Push $x$ onto the top of the stack. - $\texttt{POP}$: Discard the top element of the stack. - $\texttt{INV}$: Take out the top element and push its negation. - $\texttt{DUP}$: Push another number equal to the top element. - $\texttt{SWP}$: Swap the top two elements. - $\texttt{ADD}$: Pop the top two elements, add them, and push the result. - $\texttt{SUB}$: Pop the top two elements, subtract the first popped from the second popped, and push the result. - $\texttt{MUL}$: Pop the top two elements, multiply them, and push the result. - $\texttt{DIV}$: Pop the top two elements, integer-divide the second popped by the first popped, and push the result. - $\texttt{MOD}$: Pop the top two elements, take the second popped modulo the first popped, and push the result. - $\texttt{END}$: Terminate this program. Then, Xiao Z used the above 11 operations to write a unary function $f(x)$. The value $x$ is the initial element pushed into the stack. After a sequence of operations, when the function ends, normally the stack will contain exactly one element. The remaining element is taken as the return value of $f(x)$. Xiao Z has $n$ queries. For each value $x$, he asks what $f(x)$ is as computed by the function above. However, the machine is too old and runs too slowly, and Xiao Z is impatient, so please write a program to help him compute his queries $f(x)$. Also, because this machine is too fragile, if during the computation any absolute value exceeds $1000000000$, the machine will fail.

Input Format

The input first contains several lines, each consisting of one of the 11 operations above, describing the operations of the function $f(x)$. The function is guaranteed to end with $\texttt{END}$. Then an integer $n$, the number of queries. Then $n$ lines follow, each with an integer $x$, representing a query for the value $f(x)$. The input is not guaranteed to be valid.

Output Format

Output $n$ lines, each representing the result of one query, following these rules: - If the stack does not end with exactly one element, output `ERROR`. - If during computation any absolute value exceeds $1000000000$, output `ERROR`. - If the input data is invalid and causes an early exit, output `ERROR`. - Otherwise, output the corresponding $f(x)$.

Explanation/Hint

Constraints and Notes For all test points, the number of function operations does not exceed $2000$, $1 \leq n \leq 2000$, and $|x| \leq 10^{9}$. Translated by ChatGPT 5