結果
| 問題 |
No.50 おもちゃ箱
|
| コンテスト | |
| ユーザー |
lam6er
|
| 提出日時 | 2025-03-26 15:56:27 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 48 ms / 5,000 ms |
| コード長 | 2,048 bytes |
| コンパイル時間 | 408 ms |
| コンパイル使用メモリ | 83,040 KB |
| 実行使用メモリ | 61,940 KB |
| 最終ジャッジ日時 | 2025-03-26 15:56:56 |
| 合計ジャッジ時間 | 3,290 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 38 |
ソースコード
import itertools
def main():
import sys
input = sys.stdin.read().split()
ptr = 0
N = int(input[ptr])
ptr += 1
A = list(map(int, input[ptr:ptr+N]))
ptr += N
M = int(input[ptr])
ptr += 1
B = list(map(int, input[ptr:ptr+M]))
ptr += M
sumA = sum(A)
if not B:
print(-1)
return
maxB = max(B)
if any(a > maxB for a in A):
print(-1)
return
sumB = sum(B)
if sumA > sumB:
print(-1)
return
maxA = max(A)
for k in range(1, M + 1):
for combo in itertools.combinations(B, k):
sumC = sum(combo)
if sumC < sumA:
continue
maxC = max(combo)
if maxC < maxA:
continue
toys_sorted = sorted(A, reverse=True)
boxes_sorted = sorted(combo, reverse=True)
memo = {}
def backtrack(index, remaining):
if index == len(toys_sorted):
return True
current_toy = toys_sorted[index]
key = (index, tuple(remaining))
if key in memo:
return memo[key]
for i in range(len(remaining)):
if i > 0 and remaining[i] == remaining[i-1]:
continue
if remaining[i] >= current_toy:
new_remaining = list(remaining)
new_remaining[i] -= current_toy
new_remaining_sorted = sorted(new_remaining, reverse=True)
if backtrack(index + 1, new_remaining_sorted):
memo[key] = True
return True
memo[key] = False
return False
initial_remaining = boxes_sorted.copy()
if backtrack(0, initial_remaining):
print(k)
return
print(-1)
if __name__ == "__main__":
main()
lam6er