eolymp
bolt
Try our new interface for solving problems
Problems

“Roman” corridor

“Roman” corridor

Let’s remind the notation of Roman numerals. The notation is for natural numbers from \textbf{1} to \textbf{3999}. Capital Latin letters '\textbf{I}', '\textbf{V}', '\textbf{X}', '\textbf{L}', '\textbf{C}', '\textbf{D}', '\textbf{M}' and their combinations are used to represent so called atomic numbers (see the table below). To put down a number N it is necessary to find the greatest atomic number \textbf{K} which is not greater then \textbf{N}. The Roman notation of the found number \textbf{K} is put down, and the process is repeated for (\textbf{N-K}). The Roman numerals are put down from left to right without spaces. Thus, the number \textbf{999} in the Roman notation is \textbf{CMXCIX} (but not \textbf{IM}, as somebody may think). You need to pass through a rectangular corridor. The corridor is \textbf{n} meters width and \textbf{m} meters long (\textbf{1} ≤ \textbf{n}, \textbf{m} ≤ \textbf{15}, \textbf{n*m} ≤ \textbf{100}). It is laid out by square tiles. Each tile is \textbf{1} meter width and has a 'Roman' symbol on it: '\textbf{I}', '\textbf{V}', '\textbf{X}', '\textbf{L}', '\textbf{C}', '\textbf{D}' or '\textbf{M}'. When passing the corridor, you move from one tile to another. From the current tile you may only move to one of adjacent tiles, vertically or horizontally (but not across). You start at the left and end at the right (see the picture below). \includegraphics{https://static.e-olymp.com/content/b8/b82d5a6104c65a95bce9d1f0d8d502c4cda2b3c6.jpg} Can you pass through the corridor so that the sequence of symbols on the tiles composing your path was a correct number in the Roman notation? Among all possible solutions you need to find the minimal number. \InputFile The input data are in the first line contains numbers \textbf{n} and \textbf{m}, separated by one or more spaces. Each of the next \textbf{n }lines consists of \textbf{m} characters describing tiles. \OutputFile The output file contains one line with the found Roman number or the word \textbf{NO} if it is impossible to pass through the corridor in the required way.
Time limit 1 second
Memory limit 64 MiB
Input example #1
3 3
CMM
IXI
LMC
Output example #1
CMXI
Source ACM Programming Contest 2005, Minsk, October 2005