結果

問題 No.4 おもりと天秤
ユーザー tshigitshigi
提出日時 2016-08-01 15:51:59
言語 Ruby
(3.3.0)
結果
AC  
実行時間 126 ms / 5,000 ms
コード長 515 bytes
コンパイル時間 61 ms
コンパイル使用メモリ 11,392 KB
実行使用メモリ 18,732 KB
最終ジャッジ日時 2023-09-08 16:47:42
合計ジャッジ時間 3,324 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 81 ms
15,104 KB
testcase_01 AC 79 ms
15,172 KB
testcase_02 AC 79 ms
15,296 KB
testcase_03 AC 79 ms
15,244 KB
testcase_04 AC 79 ms
15,248 KB
testcase_05 AC 109 ms
17,412 KB
testcase_06 AC 79 ms
15,252 KB
testcase_07 AC 111 ms
17,704 KB
testcase_08 AC 80 ms
15,292 KB
testcase_09 AC 80 ms
15,128 KB
testcase_10 AC 115 ms
17,712 KB
testcase_11 AC 78 ms
15,088 KB
testcase_12 AC 78 ms
15,144 KB
testcase_13 AC 77 ms
15,292 KB
testcase_14 AC 79 ms
15,288 KB
testcase_15 AC 78 ms
15,088 KB
testcase_16 AC 78 ms
15,132 KB
testcase_17 AC 77 ms
15,236 KB
testcase_18 AC 126 ms
18,732 KB
testcase_19 AC 105 ms
17,256 KB
testcase_20 AC 104 ms
16,904 KB
testcase_21 AC 104 ms
17,424 KB
testcase_22 AC 109 ms
17,668 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

inputs = STDIN.readlines.map(&:chomp)
N = inputs[0].to_i
Ws = inputs[1].split(/\s+/).map(&:to_i)

total = Ws.inject(:+)
unless total % 2 == 0
  puts 'impossible'
  exit
end

goal = total / 2
memos = Array.new(N + 1) { Hash.new }

def dp(i, g, memos)
  if g == 0
    res = true
  elsif i == N || g < 0
    res = false
  elsif memos[i].key?(g)
    res = memos[i][g]
  else
    res = dp(i + 1, g, memos) || dp(i + 1, g - Ws[i], memos)
  end
  memos[i][g] = res
end

puts dp(0, goal, memos) ? 'possible' : 'impossible'
0