๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ํŒŒ๋„๋ฐ˜ ์ˆ˜์—ด BOJ #9461

by seolhee2750 2021. 11. 16.
๋ฌธ์ œ

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

 

9461๋ฒˆ: ํŒŒ๋„๋ฐ˜ ์ˆ˜์—ด

์˜ค๋ฅธ์ชฝ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ์‚ผ๊ฐํ˜•์ด ๋‚˜์„  ๋ชจ์–‘์œผ๋กœ ๋†“์—ฌ์ ธ ์žˆ๋‹ค. ์ฒซ ์‚ผ๊ฐํ˜•์€ ์ •์‚ผ๊ฐํ˜•์œผ๋กœ ๋ณ€์˜ ๊ธธ์ด๋Š” 1์ด๋‹ค. ๊ทธ ๋‹ค์Œ์—๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ณผ์ •์œผ๋กœ ์ •์‚ผ๊ฐํ˜•์„ ๊ณ„์† ์ถ”๊ฐ€ํ•œ๋‹ค. ๋‚˜์„ ์—์„œ ๊ฐ€์žฅ ๊ธด ๋ณ€์˜

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
t = int(input())
memory = [1, 1, 1, 2, 2, 3, 4, 5, 7, 9]
n = []
for _ in range(0, t): n.append(int(input()))

if max(n) > 10:
    num = 10
    while num < max(n):
        memory.append(memory[num-1] + memory[num-5])
        num += 1

for i in n: print(memory[i-1])

๐Ÿ‘‰ DP ๋ฌธ์ œ๋กœ, ์ ํ™”์‹์„ ๊ตฌํ•˜๊ณ  ๋ฉ”๋ชจ์ด์ œ์ด์…˜ ํ™œ์šฉํ•˜๋Š”๊ฒŒ ํฌ์ธํŠธ!

 

[์ ํ™”์‹]

  • p(1) = 1
  • p(2) = 1
  • p(3) = 1
  • p(4) = 2
  • p(5) = 2
  • p(6) = 3 = p(5) + p(1)
  • p(7) = 4 = p(6) + p(2)

=> p(n) = p(n-1) + p(n-5) (n > 5)

(์ด ์ ํ™”์‹์€ ์‚ฌ์‹ค ์ด๋ ‡๊ฒŒ ์จ๋ณด๋Š” ๊ฒƒ๋ณด๋‹ค, ๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ๊ทธ๋ฆผ์—์„œ

ํ•ด๋‹น ์ˆซ์ž๊ฐ€ ์“ฐ์—ฌ์ง„ ์‚ผ๊ฐํ˜• ํ•œ ๋ณ€์„ ์ด๋ฃจ๋Š”๊ฒŒ ๋ช‡ ๋ฒˆ์งธ ์‚ผ๊ฐํ˜•๋“ค์˜ ๋ณ€์œผ๋กœ ์ด๋ฃจ์–ด์กŒ๋Š”์ง€๋ฅผ ๋ณด๋ฉด ๋ฐ”๋กœ ์•Œ ์ˆ˜ ์žˆ๋‹ค.)

 

[ํ’€์ด ์„ค๋ช…]

  • ์ด๋ฏธ ๊ตฌํ•ด์ง„ 10๊นŒ์ง€์˜ ๋ณ€์˜ ๊ธธ์ด๋Š” ๋ฏธ๋ฆฌ memory ๋ฆฌ์ŠคํŠธ์— ๋„ฃ์–ด๋‘๊ณ ,
    ๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ์ž…๋ ฅ์„ ๋ชจ๋‘ ๋ฐ›์€ ํ›„ ๊ทธ ์ž…๋ ฅ๋“ค ์ค‘ ๊ฐ€์žฅ ํฐ ์ˆ˜๊ฐ€ 10๋ณด๋‹ค ํด ๊ฒฝ์šฐ์—๋งŒ
    memory ๋ฆฌ์ŠคํŠธ์— ์—ฐ์‚ฐ ๊ฐ’์„ ์ถ”๊ฐ€ํ•ด์ฃผ๋Š” ๋ฐ˜๋ณต ์—ฐ์‚ฐ์„ ์‹œํ–‰ํ•ด์ฃผ์—ˆ๋‹ค.
  • ๋ฐ˜๋ณต ์—ฐ์‚ฐ์€ ์œ„์—์„œ ๊ตฌํ•œ ์ ํ™”์‹์„ ์ด์šฉํ•˜์—ฌ, while๋ฌธ์œผ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ๊ทธ๋ฆผ์„ ๋ณด๊ณ  ๋ฐ”๋กœ ์ ํ™”์‹์„ ๋– ์˜ฌ๋ฆด ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€๊ณ , ๊ธˆ๋ฐฉ ํ’€์—ˆ๋‹ค.

๋Œ“๊ธ€