Reverse Roman Notation

Time limit1sMemory limit128 MB

Problem

Hermes Poseidon (HP) has produced a new calculator, the HP CXX, using the very latest in modern technology. It supports the four basic arithmetic operations on integer values from I to MMMMCMXCIX.

In this problem you simulate the HP CXX. Each line of input is one of the following:

  • A Roman numeral for a positive integer between I (1) and MMMMCMXCIX (4999). Its value is pushed onto the top of a virtual stack.
  • An arithmetic operator +, -, *, or /, applied to the top two values of the stack.
  • The = operator, a request to print the value currently on top of the stack (in Roman numerals).

The operators behave as follows. Let the topmost value be the first number and the value just below it be the second number.

  • +, *: push (second + first) or (second × first).
  • -: push (second − first), i.e. subtract the first number from the second.
  • /: push (second ÷ first) using integer division, i.e. divide the second number by the first. If the divisor (the first number) is 0, print division by zero exception, then push the dividend (the second number) back onto the stack, but not the divisor.

If an operator is requested but there are not enough numbers on the stack, print stack underflow and leave the stack unchanged. This applies both to the binary operators + - * / and to the print operator =.

If = is asked to print a value that is 0 or less, or greater than MMMMCMXCIX (4999), print out of range exception and move on to the next line of input.

Roman numerals. Each letter stands for a value:

Roman numeralValue
I1
V5
X10
L50
C100
D500
M1000

Letters written in sequence are added together, e.g. XXX = 10 + 10 + 10 = 30 and LXI = 50 + 10 + 1 = 61. When a smaller value is written before a larger one it is subtracted instead, e.g. IV = 5 − 1 = 4 and XC = 100 − 10 = 90. The usual rules apply:

  • Except for M, do not write more than three of the same letter in a row.
  • Only subtract powers of ten (I, X, or C). Write XLV for 45, not VL.
  • Subtract only a single letter. Write VIII for 8 (not IIX) and XIX for 19 (not IXX).
  • Do not subtract a letter from one more than ten times greater: I may be subtracted only from V or X, and X only from L or C (so MIM is illegal).

Input

Each line of input is one of:

  • A Roman numeral between I and MMMMCMXCIX, or
  • An arithmetic operator +, -, *, /, or the print operator =.

Input ends at end-of-file.

Output

Produce one line per event, in the order the events occur:

  • For each = operation, the value on top of the stack written in Roman numerals.
  • Whenever an error occurs, the corresponding message on a line by itself:
    • division by zero exception
    • stack underflow
    • out of range exception

No other output is produced.