結果

問題 No.708 (+ー)の式
ユーザー TANIGUCHI KousukeTANIGUCHI Kousuke
提出日時 2019-12-20 12:31:20
言語 Ruby
(3.3.0)
結果
AC  
実行時間 83 ms / 2,000 ms
コード長 541 bytes
コンパイル時間 138 ms
コンパイル使用メモリ 11,328 KB
実行使用メモリ 15,324 KB
最終ジャッジ日時 2023-09-22 11:27:10
合計ジャッジ時間 2,424 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 78 ms
15,116 KB
testcase_01 AC 77 ms
15,112 KB
testcase_02 AC 78 ms
15,168 KB
testcase_03 AC 80 ms
15,088 KB
testcase_04 AC 80 ms
15,128 KB
testcase_05 AC 83 ms
15,028 KB
testcase_06 AC 78 ms
15,320 KB
testcase_07 AC 79 ms
15,116 KB
testcase_08 AC 78 ms
15,252 KB
testcase_09 AC 78 ms
15,108 KB
testcase_10 AC 79 ms
15,116 KB
testcase_11 AC 78 ms
15,300 KB
testcase_12 AC 78 ms
15,284 KB
testcase_13 AC 79 ms
15,324 KB
testcase_14 AC 79 ms
15,164 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

def parse(s)
  root = []
  stack = [root]
  s.scan(/\d+|\D/) do |t|
    if t == '('
      stack << []
    elsif t == ')'
      st = stack.pop
      stack.last << st
    elsif t == '+' || t == '-'
      stack.last << t
    else
      stack.last << t.to_i
    end
  end
  root
end

def evaluate(ast)
  return ast if ast.instance_of?(Integer)
  ast.each_with_index.inject(0) do |s,(t,i)|
    next s if t.instance_of?(String)
    (i == 0 || ast[i - 1] == '+') ? (s + evaluate(t)) : (s - evaluate(t))
  end
end

puts evaluate(parse(gets.chomp))

0