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

๋ณธ๋ฌธ ์ œ๋ชฉ

[๋ฐฑ์ค€(BOJ)] 2579๋ฒˆ: ๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ (Dynamic Programming , C++)

PROGRAMMING/Algorithm

by koharin 2021. 2. 22. 17:10

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

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


BOJ:2156๋ฒˆ(ํฌ๋„์ฃผ ์‹œ์‹) ๋ฌธ์ œ๋ฅผ ์ฐธ๊ณ ํ•ด์„œ ์ ํ™”์‹์„ ์ƒ๊ฐํ–ˆ๋‹ค.

 

  • ์ ํ™”์‹์—์„œ DP[i-3]์ด ์‚ฌ์šฉ๋˜๋ฏ€๋กœ, 0~2๋ฒˆ์งธ์— ๋Œ€ํ•œ ์ดˆ๊ธฐ๊ฐ’์ด ํ•„์š”ํ•˜๋‹ค.
    • DP[0] = A[0]
    • DP[1] = max(A[1], A[1] + A[0])
    • DP[2] = max(A[1] + A[2], A[0] + A[2])
  • 3๋ฒˆ์งธ๋ถ€ํ„ฐ๋Š” ์ ํ™”์‹์„ ์‚ฌ์šฉํ•œ๋‹ค.
    • i-1๋ฒˆ์งธ๋ฅผ ํฌํ•จํ•˜๋Š” ๊ฒฝ์šฐ DP[i] = DP[i-3] + DP[i-1] + DP[i]
    • i-1๋ฒˆ์งธ๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ DP[i] = DP[i-2] + DP[i]
    • ์ด ๋‘ ๊ฒฝ์šฐ์— ๋Œ€ํ•œ max ๊ฐ’์„ DP[i]๋กœ ๊ฐ€์ ธ๊ฐ„๋‹ค.

 

A[0] 10
A[1] 20
A[2] 15
A[3] 25
A[4] 10
A[5] 20

์œ„์™€ ๊ฐ™์ด ํ…Œ์ŠคํŠธ์ผ€์ด์Šค๊ฐ€ ์žˆ์„ ๋•Œ, DP[3]๋ถ€ํ„ฐ๋Š” A[0] + A[1] + A[3]์„ ํ•˜๋Š” ๊ฒฝ์šฐ (DP[i-2] + A[i])์™€ A[0] + A[2] + A[3] (DP[i-3] + A[i-1] + A[i])๊ฐ€ ์žˆ๊ณ , ๋‘ ๊ฒฝ์šฐ์—์„œ ๋” ํฐ 55๋ฅผ DP[3]์— ์ €์žฅํ•œ๋‹ค.

 

DP[0]: 10
DP[1]: 30
DP[2]: 35
DP[3]: 55
DP[4]: 65
DP[5]: 75

DP๋Š” ์œ„์™€ ๊ฐ™์œผ๋ฉฐ, ๋งˆ์ง€๋ง‰์€ ํ•ญ์ƒ ํฌํ•จ๋˜๋ฏ€๋กœ DP[n-1]์„ ์ถœ๋ ฅํ•œ๋‹ค.

 

 

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


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

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

    for(int i=0; i<n; i++) scanf("%d", &A[i]);

    DP[0] = A[0];
    DP[1] = max(A[1], A[0] + A[1]);
    DP[2] = max(A[1] + A[2], A[0] + A[2]);

    for(int i=3; i<n; i++){
        DP[i] = max(DP[i-2] + A[i], DP[i-3] + A[i-1] + A[i]);
    }

    printf("%d", DP[n-1]); // ๋งˆ์ง€๋ง‰์€ ํ•ญ์ƒ ํฌํ•จ์ด๋ฏ€๋กœ
}

 

 

๐Ÿ‘ ๊ฒฐ๊ณผ


 

728x90
๋ฐ˜์‘ํ˜•

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