結果

問題 No.4 おもりと天秤
ユーザー magurogumamaguroguma
提出日時 2017-08-06 00:58:59
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
RE  
実行時間 -
コード長 1,430 bytes
コンパイル時間 164 ms
コンパイル使用メモリ 12,544 KB
実行使用メモリ 19,072 KB
最終ジャッジ日時 2024-04-20 01:55:36
合計ジャッジ時間 2,700 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

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(10000)] for b in range(100)]

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