์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[๋ฐฑ์ค€(BOJ)] 9461๋ฒˆ: ํŒŒ๋„๋ฐ˜ ์ˆ˜์—ด (Dynamic Programming, C++)

PROGRAMMING/Algorithm

by koharin 2021. 2. 23. 14:42

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“ ๋ฌธ์ œํ’€์ด ๊ณผ์ •


P(n) = 1 (0 <= n < 3)
P(n) = P(n-2) + P(n-3) (n >= 3)

0 ์ด์ƒ 2 ์ดํ•˜์˜ ์ˆ˜์— ๋Œ€ํ•ด์„œ๋Š” 1์˜ ๊ฐ’์„ ๊ฐ–๊ณ , 3 ์ด์ƒ๋ถ€ํ„ฐ๋Š” ์ ํ™”์‹ F(n) = F(n-2) + F(n-3) ์ด ๋œ๋‹ค.

 

n = 3 P(3) = P(1) + P(0) = 1 + 1 = 2
n = 4 P(4) = P(2) + P(1) = 1 + 1 = 2
n = 5 P(5) = P(3) + P(2) = 2 + 1 = 3
n = 6 P(6) = P(4) + P(3) = 2 + 2 = 4
n = 7 P(7) = P(5) + P(4) = 3 + 2 = 5
n = 8 P(8) = P(6) + P(5) = 4 + 3 = 7
n = 9 P(9) = P(7) + P(6) = 5 + 4 = 9
n = 10 P(10) = P(8) + P(7) = 7 + 5 = 12
...

 

์ฃผ์˜ํ•  ์ ์ด, N์ด 100๊ฐ™์ด ์ปค์ง€๋ฉด integer ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๊ธฐ ๋•Œ๋ฌธ์— python ๊ฐ™์ด integer ๋ฒ”์œ„๊ฐ€ ํฌ์ง€ ์•Š์€ C, C++ ๋“ฑ์€ ๋ฒ”์œ„๋ฅผ ์‹ ๊ฒฝ์จ์ค˜์•ผ ํ•œ๋‹ค. long ํ˜•์œผ๋กœ ์ˆ˜์—ด P์˜ ํ˜•์„ ๋ฐ”๊ฟ”์ฃผ๊ณ , ์ถœ๋ ฅ ์‹œ %d๊ฐ€ ์•„๋‹Œ %ld๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

๐Ÿ’ป C++ ์ œ์ถœ์ฝ”๋“œ


#include <stdio.h>
#include <deque>
using namespace std;

int main(){
    int T;
    scanf("%d", &T);
    for(int i=0; i<T; i++){
        int N;
        scanf("%d", &N);
        deque<long long> P(N, 0);

        for(int i=0; i<3; i++){
            P[i] = 1;
        }
        for(int i=3; i<N; i++){
            P[i] = P[i-2] + P[i-3];
        }
        printf("%ld\n", P[N-1]);
    }
}

 

 

๐Ÿ‘ ๊ฒฐ๊ณผ


728x90
๋ฐ˜์‘ํ˜•

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ