λ°μν
π€λ¬Έμ ν΄κ²°
-
D3 | DP( Knapsack )
π¨ λ μμκ³ λ¦¬μ¦
π¨ κ° μμ΄ν μ λν΄μ κ°λ°©μ ν¬κΈ°λ₯Ό 0λΆν° 1μ© μ΅λ무κ²κΉμ§ λλ €κ°λ©° κ³μ°.
π¨ κ°λ°©μ ν¬κΈ°κ° ν΄λΉ μμ΄ν μ 무κ²λ³΄λ€ μμΌλ©΄ μμ΄ν μ λ£μ§ λͺ»νλ€. μ΄μ κΉμ§μ 무κ²μ κ°μΉ μ μ©
π¨ κ°λ°©μ ν¬κΈ°κ° ν΄λΉ μμ΄ν μ 무κ²λ³΄λ€ ν¬λ©΄ μμ΄ν μ λ£μμ§ λ§μ§ μ ννλ€.
π¨π¨ μ΄μ κΉμ§μ 무κ²μ κ°μΉ vs (μ΄μ κΉμ§μ λ¬΄κ² - νμ¬ μμ΄ν μ 무κ²)μ κ°μΉ + νμ¬ μμ΄ν μ κ°μΉ
π»μμ€ μ½λ
# μ
λ ₯
T = int(input())
Ns = []
for tc in range(T):
N, K = map(int, input().split())
items = [list(map(int, input().split())) for _ in range(N)]
Ns.append((N, K, items))
# νμ΄
results = []
for tc in range(T):
N, K, items = Ns[tc]
dp = [[0] * (K + 1) for _ in range(N + 1)]
for i in range(1, len(dp)):
v, c = items[i - 1]
for j in range(1, len(dp[i])):
# κ°λ°©μ μμ΄ν
μ΄ λ€μ΄ κ° μ μμΌλ©΄
if j >= v:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - v] + c)
else:
dp[i][j] = dp[i - 1][j]
results.append(dp[-1][-1])
# μΆλ ₯
for tc in range(T):
print(f'#{tc + 1} {results[tc]}')
πλ¬Έμ νμΈ
μΆμ²: SW Expert Academy
λ°μν
'Algorithm Problem > Python' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[python] SWEA - 3307. μ΅μ₯ μ¦κ° λΆλΆ μμ΄ (0) | 2020.12.19 |
---|---|
[python] SWEA - 3304. μ΅μ₯ κ³΅ν΅ λΆλΆ μμ΄ (0) | 2020.12.18 |
[python] SWEA - 3975. μΉλ₯ λΉκ΅νκΈ° (0) | 2020.12.16 |
[python] SWEA - 4371. νꡬμ λ€μ΄μ€λ λ°° (0) | 2020.12.15 |
[python] SWEA - 4579. μΈμμ λͺ¨λ ν°λ¦°λ둬 2 (0) | 2020.12.14 |