結果
問題 | No.4 おもりと天秤 |
ユーザー | maguroguma |
提出日時 | 2017-08-06 17:20:52 |
言語 | Python3 (3.12.2 + numpy 1.26.4 + scipy 1.12.0) |
結果 |
AC
|
実行時間 | 213 ms / 5,000 ms |
コード長 | 2,245 bytes |
コンパイル時間 | 504 ms |
コンパイル使用メモリ | 11,064 KB |
実行使用メモリ | 16,660 KB |
最終ジャッジ日時 | 2023-09-08 17:33:34 |
合計ジャッジ時間 | 3,375 ms |
ジャッジサーバーID (参考情報) |
judge12 / judge11 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 24 ms
8,556 KB |
testcase_01 | AC | 19 ms
8,740 KB |
testcase_02 | AC | 47 ms
9,660 KB |
testcase_03 | AC | 37 ms
9,140 KB |
testcase_04 | AC | 47 ms
9,616 KB |
testcase_05 | AC | 200 ms
16,652 KB |
testcase_06 | AC | 21 ms
8,528 KB |
testcase_07 | AC | 201 ms
16,608 KB |
testcase_08 | AC | 64 ms
16,532 KB |
testcase_09 | AC | 213 ms
16,660 KB |
testcase_10 | AC | 200 ms
16,508 KB |
testcase_11 | AC | 31 ms
9,012 KB |
testcase_12 | AC | 23 ms
8,680 KB |
testcase_13 | AC | 23 ms
8,556 KB |
testcase_14 | AC | 25 ms
8,780 KB |
testcase_15 | AC | 23 ms
8,604 KB |
testcase_16 | AC | 32 ms
9,080 KB |
testcase_17 | AC | 31 ms
9,004 KB |
testcase_18 | AC | 206 ms
16,652 KB |
testcase_19 | AC | 200 ms
16,604 KB |
testcase_20 | AC | 201 ms
16,496 KB |
testcase_21 | AC | 202 ms
16,560 KB |
testcase_22 | AC | 202 ms
16,520 KB |
ソースコード
# -*- coding: utf-8 -*- # 動的計画法(メモ化探索),深さ優先探索: depth first searchの活用 def equal_balance(dp, N, W): weight_sum = sum(W) if weight_sum % 2 == 1: return 'impossible' else: weight_sum /= 2 recurrence_formula(dp, N, W) # if dfs(0, int(weight_sum), dp, N, W): if dp[0][int(weight_sum)]: return 'possible' else: return 'impossible' """ i番目以降の錘を使って合計jの重量にできればTrueを返す(メモには可否を表すbool値を記す) メモ化再帰による実装 この他にも,dp[i][j]にi番目以降の錘を加えた総重量jが目的の総重量であるか否かを記録する方法もある """ def dfs(i, j, dp, N, W): #すでに調べたものは再利用する if dp[i][j] != None: return dp[i][j] is_possible = False if i == N: #錘が存在しない場合は不可能 is_possible = False elif j == 0: #総重量が0場合はTrueを返す(どこかで当初の総重量を達成できたことを意味するため) is_possible = True elif j < W[i]: #i番目の錘が総重量以上の場合は,その錘は使えない #if j == 0: # is_possible = True #else: is_possible = dfs(i+1, j, dp, N, W) else: #i番目の錘を使える場合は,使うときと使わない時の場合を両方考慮する is_possible = (dfs(i+1, j, dp, N, W) or dfs(i+1, j-W[i], dp, N, W)) dp[i][j] = is_possible return is_possible """ 漸化式による実装 2次元配列dpには,i番目以降の錘を使って合計jの重量にできればTrueを記録 """ def recurrence_formula(dp, N, W): for j in range(10001): dp[N][j] = False for i in range(N-1, -1, -1): for j in range(0, 10001): if j == W[i]: dp[i][j] = True elif j < W[i]: dp[i][j] = dp[i+1][j] else: dp[i][j] = (dp[i+1][j] or dp[i+1][j-W[i]]) N = int(input()) W = list(map(int, input().split())) dp = [[None for a in range(10001)] for b in range(N+1)] print(equal_balance(dp, N, W))