[BOJ][๐ŸŸก4][๋ฐฑ์ค€#14852] ํƒ€์ผ ์ฑ„์šฐ๊ธฐ 3

์ž‘์„ฑ:    

์—…๋ฐ์ดํŠธ:

์นดํ…Œ๊ณ ๋ฆฌ:

ํƒœ๊ทธ: , , ,

๋ฌธ์ œ ์ถœ์ฒ˜

BAEKJOON Online Judge #14852


๋ฌธ์ œ

2ร—N ํฌ๊ธฐ์˜ ๋ฒฝ์„ 2ร—1, 1ร—2,ย 1ร—1ย ํฌ๊ธฐ์˜ ํƒ€์ผ๋กœ ์ฑ„์šฐ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผย ๊ตฌํ•ด๋ณด์ž.


์ž…๋ ฅ

์ฒซ์งธ ์ค„์— N(1 โ‰ค N โ‰ค 1,000,000)์ด ์ฃผ์–ด์ง„๋‹ค.


์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ 1,000,000,007๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.


์˜ˆ์ œ

์˜ˆ์ œ 1

์ž…๋ ฅ

1


์ถœ๋ ฅ

2


์˜ˆ์ œ 2

์ž…๋ ฅ

2


์ถœ๋ ฅ

7


์˜ˆ์ œ 3

์ž…๋ ฅ

3


์ถœ๋ ฅ

22


My Sol

def main():
    M = 1000000007
    ans = [0, 2, 7]
    N = int(input())
    if N < 3: return ans[N]

    cnt, cross = 2, 1
    a, b, c = ans
    while cnt < N:
        new_c = (2*cross+3*b+2*c)%M
        a, b, c = b, c, new_c
        cnt += 1
        cross += a
        cross %= M

    return c

print(main())

DP๋ฅผ ํ™œ์šฉํ•ด ํ‘ธ๋Š” ๋ฌธ์ œ์˜€๋‹ค.

image

๋ฌธ์ œ ํ’€์ด์˜ ๊ด€๊ฑด์€ dp[N-3] ~ dp[1] ์˜์—ญ์ฒ˜๋Ÿผ ๊ต์ฐจํ•ด์„œ ๋ฐ˜๋ณต๋˜๋Š” ๊ฒƒ์ด๋‹ค. ์ด๋Š” 2๊ฐ€์ง€์”ฉ ์ด๊ณ , dp[N-3] ๋ถ€ํ„ฐ dp[1] ๊นŒ์ง€ ๊ฐœ์ˆ˜์— 2๋ฐฐ์”ฉ ํ•˜์—ฌ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

๋˜ํ•œ ๋˜๋‹ค๋ฅธ ๋…ธํ•˜์šฐ๋Š” ๋ชจ๋“  dp ๋ฐฐ์—ด์„ ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ, pythonicํ•˜๊ฒŒ ๋ณ€์ˆ˜ 3๊ฐœ๋กœ ์ด์ „ ๊ฐ’์„ ๋ฏธ๋ฃจ๋ฉฐ ์ €์žฅ, ๊ฐฑ์‹ ํ•˜์—ฌ ํ’€์–ด๋‚ธ ๊ฒƒ์ด๋‹ค.

new_c = (2*cross+3*b+2*c)%M
a, b, c = b, c, new_c


๊ฒฐ๊ณผ

๋งž์•˜์Šต๋‹ˆ๋‹ค!!

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ