結果

問題 No.518 ローマ数字の和
ユーザー simansiman
提出日時 2022-07-24 11:12:25
言語 Ruby
(3.3.0)
結果
AC  
実行時間 85 ms / 2,000 ms
コード長 1,098 bytes
コンパイル時間 278 ms
コンパイル使用メモリ 11,240 KB
実行使用メモリ 15,340 KB
最終ジャッジ日時 2023-09-20 09:35:45
合計ジャッジ時間 3,128 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 85 ms
15,340 KB
testcase_01 AC 84 ms
15,204 KB
testcase_02 AC 83 ms
15,148 KB
testcase_03 AC 83 ms
15,124 KB
testcase_04 AC 83 ms
15,272 KB
testcase_05 AC 83 ms
15,284 KB
testcase_06 AC 83 ms
15,252 KB
testcase_07 AC 83 ms
15,036 KB
testcase_08 AC 81 ms
15,088 KB
testcase_09 AC 81 ms
15,168 KB
testcase_10 AC 83 ms
15,040 KB
testcase_11 AC 82 ms
15,124 KB
testcase_12 AC 82 ms
15,252 KB
testcase_13 AC 84 ms
15,080 KB
testcase_14 AC 83 ms
15,120 KB
testcase_15 AC 82 ms
15,140 KB
testcase_16 AC 82 ms
15,184 KB
testcase_17 AC 82 ms
15,040 KB
testcase_18 AC 82 ms
15,228 KB
testcase_19 AC 81 ms
15,036 KB
testcase_20 AC 81 ms
15,128 KB
testcase_21 AC 81 ms
15,304 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

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
0