TABLE = { "I" => 1, "V" => 5, "X" => 10, "L" => 50, "C" => 100, "D" => 500, "M" => 1000, } TABLE_R = { 1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C", 500 => "D", 1000 => "M", } def parse(str) if str.size == 1 TABLE[str] else stack = [] val = 0 str.chars.each do |s| stack << s if stack.size >= 2 && TABLE[stack[-2]] < TABLE[stack[-1]] a, b = stack.pop(2) val += TABLE[b] - TABLE[a] end end until stack.empty? a = stack.pop val += TABLE[a] end val end end def encode(val) res = "" [1000, 100, 10, 1].each do |base| d = val / base val -= d * base next if d == 0 if d <= 3 res << TABLE_R[base] * d elsif d == 4 res << TABLE_R[base] + TABLE_R[5 * base] elsif d == 9 res << TABLE_R[base] + TABLE_R[10 * base] else res << TABLE_R[5 * base] + TABLE_R[base] * (d - 5) end end res end N = gets.to_i R = gets.chomp.split val = R.map { |r| parse(r) }.sum if val >= 4000 puts "ERROR" else puts encode(val) end