結果

問題 No.626 Randomized 01 Knapsack
ユーザー NatsubiSoganNatsubiSogan
提出日時 2021-08-21 17:32:13
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 79 ms / 2,000 ms
コード長 1,173 bytes
コンパイル時間 333 ms
コンパイル使用メモリ 12,928 KB
実行使用メモリ 12,800 KB
最終ジャッジ日時 2024-04-23 08:19:08
合計ジャッジ時間 2,646 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 26 ms
11,008 KB
testcase_01 AC 26 ms
11,008 KB
testcase_02 AC 27 ms
11,008 KB
testcase_03 AC 27 ms
11,136 KB
testcase_04 AC 27 ms
11,008 KB
testcase_05 AC 26 ms
11,008 KB
testcase_06 AC 27 ms
11,136 KB
testcase_07 AC 30 ms
11,264 KB
testcase_08 AC 34 ms
11,264 KB
testcase_09 AC 42 ms
11,776 KB
testcase_10 AC 36 ms
11,520 KB
testcase_11 AC 57 ms
12,672 KB
testcase_12 AC 59 ms
12,672 KB
testcase_13 AC 54 ms
12,672 KB
testcase_14 AC 50 ms
12,672 KB
testcase_15 AC 52 ms
12,800 KB
testcase_16 AC 78 ms
12,672 KB
testcase_17 AC 53 ms
12,672 KB
testcase_18 AC 49 ms
12,672 KB
testcase_19 AC 60 ms
12,672 KB
testcase_20 AC 55 ms
12,672 KB
testcase_21 AC 49 ms
12,800 KB
testcase_22 AC 79 ms
12,672 KB
testcase_23 AC 56 ms
12,800 KB
testcase_24 AC 47 ms
12,672 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from bisect import bisect
from collections import defaultdict
from itertools import accumulate
def solve(n, W, vw):
    vw.sort(key=lambda x: x[0] / x[1], reverse=True)
    vs = []
    ws = []
    wei_to_val = defaultdict(int)
    wei_to_val[0] = 0
    for v, w in vw:
        vs.append(v)
        ws.append(w)
    cum_v, cum_w = [0] + list(accumulate(vs)), [0] + list(accumulate(ws))
    cum_v.append(cum_v[-1])
    res = cum_v[bisect(cum_w, W) - 1]
    for i, (v, w) in enumerate(vw):
        cur_w = W + cum_w[i]
        del_v = cum_v[i]
        for w2, v2 in list(wei_to_val.items()):
            if w2 + w > W: continue
            j = bisect(cum_w, cur_w - w2) - 1
            tmp_ans = v2 + cum_v[j] - del_v
            if j < n - 1:
                plus = vs[j] * (cur_w - w2 - cum_w[j]) / ws[j]
            else:
                plus = 0
            if tmp_ans + plus <= res:
                del wei_to_val[w2]
                continue
            res = max(res, tmp_ans)
            wei_to_val[w2 + w] = max(wei_to_val[w2 + w], v2 + v)
    return res
n, W = map(int, input().split())
vw = [list(map(int, input().split())) for i in range(n)]
print(solve(n, W, vw))
0