#C6768. Roman Numerals to Integer Conversion

    ID: 50564 Type: Default 1000ms 256MiB

Roman Numerals to Integer Conversion

Roman Numerals to Integer Conversion

You are given a string representing a Roman numeral. Your task is to convert the Roman numeral into its integer value. The numeral follows the standard Roman numeral rules with a twist: if the numeral is invalid (for example, it contains non-Roman characters, violates symbol repetition rules, or represents a number not in the range \(1 \leq x \leq 3999\)), then you should output -1.

The Roman numeral consists of the following symbols: I, V, X, L, C, D, and M. The numeral is interpreted from left to right, taking into account subtractive combinations (e.g., IV for 4, IX for 9). For a numeral to be valid, it must conform to these rules:

  • Only the symbols I, V, X, L, C, D, and M are allowed.
  • The symbols I, X, and C cannot appear more than three times in total, and V, L, and D cannot appear more than once.
  • The resulting integer must be between 1 and 3999, inclusive.

If any of these conditions are not met, output -1.

Your program should read input from stdin and output the result to stdout.

inputFormat

The input consists of a single line containing a non-empty string representing a Roman numeral.

Example:

XVII

outputFormat

Print a single integer which is the value of the Roman numeral, or -1 if the numeral is invalid.

Example:

17
## sample
III
3