結果

問題 No.4 おもりと天秤
ユーザー magurogumamaguroguma
提出日時 2017-08-06 01:03:21
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
TLE  
実行時間 -
コード長 1,430 bytes
コンパイル時間 278 ms
コンパイル使用メモリ 12,672 KB
実行使用メモリ 25,884 KB
最終ジャッジ日時 2024-04-20 01:56:13
合計ジャッジ時間 7,198 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 79 ms
18,944 KB
testcase_01 AC 86 ms
18,944 KB
testcase_02 AC 92 ms
19,072 KB
testcase_03 AC 88 ms
18,944 KB
testcase_04 AC 85 ms
19,072 KB
testcase_05 TLE -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

# -*- 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
        if dfs(0, int(weight_sum), dp, N, W):
            return 'possible'
        else:
            return 'impossible'

#i番目以降の錘を使って合計jの重量にできればTrueを返す(メモには可否を表すbool値を記す)
def dfs(i, j, dp, N, W):
    #すでに調べたものは再利用する
    if dp[i][j] != 0:
        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番目の錘が総重量以上の場合は,その錘は使えない
        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

N = int(input())
W = list(map(int, input().split()))
dp = [[0 for a in range(10001)] for b in range(101)]

print(equal_balance(dp, N, W))
0