ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [๋ฐฑ์ค€] 9461 ํŒŒ๋„๋ฐ˜ ์ˆ˜์—ด with Python
    PS 2022. 1. 10. 18:54
    728x90
    ๋ฐ˜์‘ํ˜•

    ๐Ÿ“Œ BOJ 9461 ํŒŒ๋„๋ฐ˜ ์ˆ˜์—ด

    ๐Ÿ’ก ์กฐ๊ฑด

    1. ์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ T๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ํ•œ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๊ณ , N์ด ์ฃผ์–ด์ง„๋‹ค.
      (1 โ‰ค N โ‰ค 100)

    2. ํŒŒ๋„๋ฐ˜ ์ˆ˜์—ด P(N)์€ ๋‚˜์„ ์— ์žˆ๋Š” ์ •์‚ผ๊ฐํ˜•์˜ ๋ณ€์˜ ๊ธธ์ด.

    3. P(1)๋ถ€ํ„ฐ P(10)๊นŒ์ง€ ์ฒซ 10๊ฐœ ์ˆซ์ž๋Š” 1, 1, 1, 2, 2, 3, 4, 5, 7, 9

    4. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋งˆ๋‹ค ์ •์ˆ˜ N์„ ์ž…๋ ฅ๋ฐ›์•„ P(N)์„ ์ถœ๋ ฅ.

    5. Dynamic Programming ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•์˜ ๋ฌธ์ œ

    ๐Ÿ–ฅ ์†Œ์Šค ์ฝ”๋“œ

    from sys import stdin
    
    dp = [0 for _ in range(101)]
    dp[0], dp[1], dp[2] = 1, 1, 1
    
    for i in range(3, 101):
        dp[i] = dp[i - 3] + dp[i - 2]
    
    for _ in range(int(stdin.readline())):
        print(dp[int(stdin.readline()) - 1])

    ๐Ÿ”– ์˜ˆ์ œ ๋ฐ ์‹คํ–‰๊ฒฐ๊ณผ

    ์˜ˆ์ œ

    2
    6
    12

    ์‹คํ–‰๊ฒฐ๊ณผ

    3
    16

    โŒจ๏ธ ๋ฌธ์ œ ํ’€์ด

    1. ๋ฌธ์ œ์—์„œ ์ด๋ฏธ ์ ํ™”์‹์„ ์งœ๋ผ๊ณ  P(1)๋ถ€ํ„ฐ P(10)๊นŒ์ง€ ์ œ๊ณตํ•ด์ฃผ์—ˆ๋‹ค.
      ๊ทœ์น™์„ ์ฐพ์•„ ์ ํ™”์‹์„ ์„ธ์›Œ๋ณด์ž๋ฉด, dp[i] = dp[i - 3] + dp[i - 2] ์ด ๋  ๊ฒƒ์ด๋‹ค.

    2. ์—ฌ๊ธฐ์„œ N์˜ ๋ฒ”์œ„๋ฅผ ์‚ดํŽด๋ณด๋ฉด 1๋ถ€ํ„ฐ 100๊นŒ์ง€ ์ด๋‹ค.

    3. ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋ฅผ 101๊ฐœ๋กœ ๋‘” ๋’ค, ๋ฌธ์ œ์—์„œ ์ œ๊ณตํ•ด์ค€ ๊ฐ’์„ ๋‹ค ๋„ฃ์–ด๋„ ์ข‹๊ณ , ์•ž์˜ ์„ธ๊ฐœ๋งŒ ๋„ฃ์–ด ์ ํ™”์‹์„ ํ†ตํ•ด
      101๊ฐœ์˜ ๋ฐฐ์—ด์„ ์ฑ„์šฐ๋Š” ๊ฒƒ๋„ ์ข‹๋‹ค.

    1. ๋ฐฐ์—ด์„ ์ฑ„์šฐ๋Š”๋ฐ์—๋Š” ํฐ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ์ง€ ์•Š์œผ๋‹ˆ, ๋ฏธ๋ฆฌ ๋ชจ๋‘ ๊ตฌํ•ด๋†“๊ณ  ํ…Œ์ŠคํŠธ์ผ€์ด์Šค๋งˆ๋‹ค ์ž…๋ ฅ์„ ๋ฐ›์•„ ์ฒ˜๋ฆฌํ–ˆ๋‹ค.
      • ์—ฌ๊ธฐ์„œ, dp ๋ฆฌ์ŠคํŠธ์˜ N-1๋ฒˆ์งธ๋ฅผ ์ถœ๋ ฅํ•˜์ง€ ์•Š์œผ๋ฉด ์—‰๋šฑํ•œ ๋‹ต์ด ๋‚˜์˜ค๊ฑฐ๋‚˜, index์—๋Ÿฌ๋ฅผ ๋ฑ‰๊ณ  ์ฃฝ์–ด๋ฒ„๋ฆด ์ˆ˜ ์žˆ์œผ๋‹ˆ ์กฐ์‹ฌํ•˜์ž.

    ๐Ÿ’พ ๋Š๋‚€์ 

    1. ๋„ˆ๋ฌด๋‚˜๋„ ์ƒ๋ƒฅํ•˜๊ณ  ์นœ์ ˆํ•œ DP๋ฌธ์ œ์˜€๋‹ค.
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.