๐ŸŒฑ → ๐ŸŒณ

[Baekjoon] 25421. ์กฐ๊ฑด์— ๋งž๋Š” ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜ - python ๋ณธ๋ฌธ

Algorithms

[Baekjoon] 25421. ์กฐ๊ฑด์— ๋งž๋Š” ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜ - python

BAY 2023. 9. 28. 15:05
728x90

https://www.acmicpc.net/problem/25421

 

25421๋ฒˆ: ์กฐ๊ฑด์— ๋งž๋Š” ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜

2๊ฐœ์˜ ์ž๋ฆฟ์ˆ˜๋ฅผ ๊ฐ–๊ณ  ์ฒซ ๋ฒˆ์งธ ์ž๋ฆฌ์˜ ์ˆซ์ž์™€ ๋‘ ๋ฒˆ์งธ ์ž๋ฆฌ์˜ ์ˆซ์ž์˜ ์ฐจ์ด๊ฐ€ 2๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์–‘์˜ ์ •์ˆ˜ 11, 12, 13, 21, 22, 23, 24, 31, 32, ... , 97, 98, 99๊ฐ€ A์— ํ•ด๋‹น๋œ๋‹ค. ๋”ฐ๋ผ์„œ ์ •๋‹ต์€ 39์ด๋‹ค.

www.acmicpc.net

๋ฌธ์ œ ์ •๋ณด

๋ฌธ์ œ ์œ ํ˜• ๋‚œ์ด๋„ ๊ฑธ๋ฆฐ ์‹œ๊ฐ„ ํ•ด๊ฒฐ ์œ ๋ฌด
DP ์‹ค๋ฒ„1 1h O

์„ค๊ณ„ ๋ฐฉ๋ฒ•

dp๋กœ ์ ‘๊ทผ

dp[n][i] = dp[n-1][i-2] + dp[n-1][i-1] + dp[n-1][i] + dp[n-1][i+1] + dp[n-1][i+2]

dp๊ฐ’์— ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ์˜ ์ˆ˜ ๋”ํ•ด๊ฐ

n๋ฒˆ์งธ ์ž๋ฆฌ ์ž์—ฐ์ˆ˜ = ์ด์ „ ๋ฒˆ์งธ ์ž๋ฆฌ ์ž์—ฐ์ˆ˜๋ณด๋‹ค 2์ด์ƒ ์ฐจ์ด๋‚˜์ง€ ์•Š๋Š”๋‹ค

๊ฐ ์ž๋ฆฌ ์ˆ˜๋Š” 0๋ณด๋‹ค ํฌ๊ณ  10๋ณด๋‹ค ์ž‘์Œ

์ฝ”๋“œ

n = int(input())
dp = [[0] * 10 for _ in range(n)]

for i in range(1, 10):
    dp[0][i] = 1

for i in range(1, n):
    for j in range(1, 10):
        t = 0
        for k in range(j - 2, j + 3):
            if 0 < k < 10:
                t += dp[i - 1][k]
                t %= 987654321
        dp[i][j] = t

print(dp) # [[0, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 3, 4, 5, 5, 5, 5, 5, 4, 3]]
ans = 0
for i in range(10):
    ans += dp[n - 1][i]
    ans %= 987654321

print(ans)

์‹œ๊ฐ„ ๋ณต์žก๋„

O(N)

์–ด๋ ค์› ๋˜ ์ 

์ ํ™”์‹์€ ๊ธˆ๋ฐฉ ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๊ตฌํ˜„์ด ์ƒ๊ฐ๋ณด๋‹ค ์˜ค๋ž˜ ๊ฑธ๋ ธ์Œ

์ฐธ๊ณ  ์ž๋ฃŒ

https://velog.io/@zjvlzld/์•Œ๊ณ ๋ฆฌ์ฆ˜-๋ฐฑ์ค€-25421-java-์ž๋ฐ”

728x90