@h = {?I => 1, ?V => 5, ?X => 10, ?L => 50, ?C => 100, ?D => 500, ?M => 1000} @h2 = @h.invert def hoge(r) m = r.size res = @h[r[m - 1]] (m-1).times do |i| if @h[r[i]] < @h[r[i + 1]] res -= @h[r[i]] else res += @h[r[i]] end end return res end def foo(x) return "ERROR" if x >= 4000 res = "" d = 1 while x > 0 if x % 10 == 9 res = @h2[d] + @h2[d * 10] + res elsif x % 10 == 4 res = @h2[d] + @h2[d * 5] + res elsif x % 10 > 4 res = @h2[d * 5] + @h2[d] * (x % 10 - 5) + res else res = @h2[d] * (x % 10) + res end x /= 10 d *= 10 end return res end n = gets.to_i puts foo(gets.chomp.split.map{|r| hoge(r)}.inject(:+))