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

๋ณธ๋ฌธ ์ œ๋ชฉ

[๋ฐฑ์ค€(BOJ)] 2156๋ฒˆ: ํฌ๋„์ฃผ ์‹œ์‹ (Dynamic Programming, C++)

PROGRAMMING/Algorithm

by koharin 2021. 2. 19. 19:24

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

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


i๋ฒˆ์งธ ๋งˆ์‹œ๋Š” ๊ฒฝ์šฐ

  • i-1๋ฒˆ์งธ ๋งˆ์‹œ๋Š” ๊ฒฝ์šฐ: DP[i] = G[i] + G[i-1] + DP[i-3]

  • i-1๋ฒˆ์งธ ์•ˆ ๋งˆ์‹œ๋Š” ๊ฒฝ์šฐ: DP[i] = G[i] + DP[i-2]

i๋ฒˆ์งธ ์•ˆ ๋งˆ์‹œ๋Š” ๊ฒฝ์šฐ

  • DP[i] = DP[i-1]

 

  • ์ตœ์ข… DP[i]๋Š” i๋ฒˆ์งธ ๋งˆ์‹œ๋Š” ๊ฒฝ์šฐ์˜ DP[i]์™€ i๋ฒˆ์งธ ์•ˆ ๋งˆ์‹œ๋Š” ๊ฒฝ์šฐ์˜ DP[i-1]์—์„œ max๋กœ ์ €์žฅํ•œ๋‹ค.

  • DP[0], DP][1] ์ดˆ๊ธฐ๊ฐ’์„ ๊ตฌํ•ด์ค˜์•ผ ํ•œ๋‹ค.

    • DP[0]์ธ ๊ฒฝ์šฐ์—๋Š” ์ด์ „์ด ์—†์œผ๋ฏ€๋กœ G[0] ๋„ฃ์–ด์ฃผ๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์€ ๊ฒฝ์šฐ์—” ํ˜„์žฌ์™€ ์ด์ „ ํฌ๋„์ฃผ ์–‘์„ ๋„ฃ์–ด์ค€๋‹ค.

 

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


#include <stdio.h>
#include <algorithm>

using namespace std;

int main(){
    int n;
    scanf("%d", &n);
    int G[n] = {0};
    int DP[n] = {0};

    for(int i=0; i<n; i++) scanf("%d", &G[i]);
    for(int i=0; i<2; i++){
        if(i==0) DP[i] = G[i];
        else DP[i] = G[i] + G[i-1];
    }
    for(int i=2; i<n; i++){
        DP[i] = max(G[i] + G[i-1] + DP[i-3], G[i] + DP[i-2]);
        DP[i] = max(DP[i-1], DP[i]);
    }

    printf("%d", DP[n-1]);
}

 

๐Ÿ‘ ๊ฒฐ๊ณผ


728x90
๋ฐ˜์‘ํ˜•

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