IVXLCDM

Interview

Time limit1sMemory limit128 MB

Summary
Given a lowercase inscription line, find the largest value of a valid Roman numeral readable as a subsequence of its letters, or 0 if none.
Level

Medium7 of 10

Topics
Greedy, String, Dynamic programming, Implementation
Solved
No attempts yet

Problem

Roman numerals are written with the seven letters I, V, X, L, C, D, and M, which stand for the values 11, 55, 1010, 5050, 100100, 500500, and 10001000 respectively. A number is written by placing these letters (repeated when necessary) from the largest value on the left to the smallest on the right. For example, 33 is written III and 7373 is written LXXIII.

The exceptions are values whose units digit is 44 or 99, whose tens digit is 4040 or 9090, and whose hundreds digit is 400400 or 900900. These use the subtractive forms IV (44), IX (99), XL (4040), XC (9090), CD (400400), and CM (900900). For instance, 2424, 3939, 4444, 4949, and 9494 are written XXIV, XXXIX, XLIV, XLIX, and XCIV.

The following rules make every value have a unique representation:

  • At most three consecutive I, X, or C may appear.
  • Each of V, L, and D may appear at most once.
  • Any number of M may appear.
  • No other subtractive combinations are allowed (for example, IC for 9999 is forbidden).

In the Middle Ages the year a building was founded was often hidden in an inscription: some of its letters were emphasized, and reading only the emphasized letters in order spelled the year as a Roman numeral. For example, the inscription Matfyz is the best schooL In prague encodes MLI, that is, 10511051.

Over time an inscription may be damaged, so it is no longer known which letters were emphasized. Given only the plain text of an inscription, determine the latest year the building could have been founded — that is, the largest value of a valid Roman numeral that can be read as a subsequence of the inscription's letters (letter case is ignored). For example, from matfyz is the best school in prague one can read MCLI, that is, 11511151.

Input

The input consists of one or more nonempty lines l1,…,lnl_1, \dots, l_n. Each line contains only lowercase letters and spaces and has length at most 10,00010{,}000 characters. Read until the end of input.

Output

For each line lil_i, output a single line containing one integer: the largest value of a Roman numeral that can be encoded in lil_i by emphasizing some of its letters, or 00 if no Roman numeral can be encoded.

Examples4

  1. Example 1

    Input
    matfyz is the best school in prague
    no year
    
    Expected output
    1151
    0
    
  2. Example 2

    Input
    x
    i
    v
    l
    c
    d
    m
    
    Expected output
    10
    1
    5
    50
    100
    500
    1000
    
  3. Example 3

    Input
    mmmm
    m
    mmm mm
    
    Expected output
    4000
    1000
    5000
    
  4. Example 4

    Input
    mmmdccclxxxviii
    
    Expected output
    3888