Algorithm/DP
[λ°±μ€] 9095 : 1, 2, 3 λνκΈ° (νμ΄μ¬)
_μμ _
2024. 8. 23. 04:33
728x90
SMALL
DP λ¬Έμ
https://www.acmicpc.net/problem/9095
π‘ νμ΄μ½λ (μ±κ³΅ 1)
import sys
t = int(sys.stdin.readline())
def dynamic(n):
dp = [0 for _ in range(n + 1)]
dp[0] = 1
dp[1] = 1
dp[2] = 2
dp[3] = 4
for i in range(4, n + 1):
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
print(dp[n])
for _ in range(t):
n = int(sys.stdin.readline())
if n == 0:
print(1)
elif n == 1:
print(1)
elif n == 2:
print(2)
elif n == 3:
print(4)
else:
dynamic(n)
μ κ·Ό λ°©μ
4λ₯Ό 1, 2, 3μΌλ‘ νννλ λ°©λ²μ 7κ°μ§μ΄λ€.
5λ₯Ό νννλ λ°©λ²μ 4μμ 1μ λνλ λ°©λ²(7κ°μ§) + 3μμ 2λ₯Ό λνλ λ°©λ²(4κ°μ§) + 2μμ 3μ λνλ λ°©λ²(2κ°μ§)μ΄ μλ€.
= μ΄ 13κ°μ§(7 + 4 + 2)
6λ₯Ό νννλ λ°©λ²μ 5μμ 1μ λνλ λ°©λ²(13κ°μ§) + 4μμ 2λ₯Ό λνλ λ°©λ²(7κ°μ§) + 3μμ 3μ λνλ λ°©λ²(4κ°μ§)μ΄ μλ€.
= μ΄ 24κ°μ§(13 + 7 + 4)
μ νμ
Nμ νννλ λ°©λ²μΌλ‘λ λ€μκ³Ό κ°λ€.
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
= dp[i-1]μμ 1μ λνλ λ°©λ² + dp[i-2]μμ 2μ λνλ λ°©λ² + dp[i-3]μμ 3μ λνλ λ°©λ²
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
λμ λ¬Έμ μ λ€λ₯Έμ
- λμ λ¬Έμ λ μ£Όμ΄μ§ λμ μ κΈμ‘μ νμ©νμ¬, κ·Έ κΈμ‘μ ν©μ΄ kμμ΄ λλλ‘ λ§λλ μ‘°ν© λ¬Έμ μ΄λ€.
- λμ μ ꡬμ±μ΄ κ°μλ°, μμκ° λ€λ₯Έ κ²μ κ°μ κ²½μ°μ΄κΈ° λλ¬Έμ΄λ€.
- μ΄ λ¬Έμ λ 1, 2, 3μ νμ©νμ¬, κ·Έ ν©μ΄ kκ° λλλ‘ λ§λλ μμ΄ λ¬Έμ μ΄λ€.
- μλ λκ°μ§ κ²½μ°λ κ°κ° λ€λ₯Έ κ²½μ°μ΄λ€.
- 1+2+1
- 2+1+1
π‘ νμ΄μ½λ (μ±κ³΅ 2)
import sys
t = int(sys.stdin.readline())
def sol(n):
dp = [0 for _ in range(n + 1)]
dp[0] = 1
for i in range(1, n + 1):
for j in range(1, 4):
if i - j >= 0:
dp[i] += dp[i - j]
print(dp[n])
for _ in range(t):
n = int(sys.stdin.readline())
sol(n)
μ°Έκ³ λ¬Έν
https://ggasoon2.tistory.com/39
728x90
LIST