๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Programmers)

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋•…๋”ฐ๋จน๊ธฐ(Level 2)

by dkswnkk 2022. 4. 18.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋•…๋”ฐ๋จน๊ธฐ

๋•…๋”ฐ๋จน๊ธฐ ๊ฒŒ์ž„์„ ํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๋•…๋”ฐ๋จน๊ธฐ ๊ฒŒ์ž„์˜ ๋•…(land)์€ ์ด Nํ–‰ 4์—ด๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๊ณ , ๋ชจ๋“  ์นธ์—๋Š” ์ ์ˆ˜๊ฐ€ ์“ฐ์—ฌ ์žˆ์Šต๋‹ˆ๋‹ค. 1ํ–‰๋ถ€ํ„ฐ ๋•…์„ ๋ฐŸ์œผ๋ฉฐ ํ•œ ํ–‰์”ฉ ๋‚ด๋ ค์˜ฌ ๋•Œ, ๊ฐ ํ–‰์˜ 4์นธ ์ค‘ ํ•œ ์นธ๋งŒ ๋ฐŸ

programmers.co.kr

 

ํ’€์ด

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int dp[100001][4];

int solution(vector<vector<int> > land)
{
    int answer = 0;
    int len = land.size();
    for(int i=0; i<4; i++) dp[0][i] = land[0][i];
    
    for(int i=1; i<len; i++){
        for(int k=0; k<4; k++){
            if(k==0) dp[i][k] = max({dp[i-1][k+1],dp[i-1][k+2],dp[i-1][k+3]})+land[i][k];
            if(k==1) dp[i][k] = max({dp[i-1][k-1],dp[i-1][k+1],dp[i-1][k+2]})+land[i][k];
            if(k==2) dp[i][k] = max({dp[i-1][k-2],dp[i-1][k-1],dp[i-1][k+1]})+land[i][k];
            if(k==3) dp[i][k] = max({dp[i-1][k-3],dp[i-1][k-2],dp[i-1][k-1]})+land[i][k];
            answer = max(answer, dp[i][k]);
        }
    }
    
    return answer;
}

 

ํ’€์ด(14๋ถ„)

์ด ๋ฌธ์ œ๋ฅผ ์ฒ˜์Œ ์‹œ๋„ํ–ˆ๋˜ ๊ฑด ํ•œ 8๊ฐœ์›” ์ „์ด์—ˆ๋˜ ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ทธ๋•Œ๋Š” ์ง€๊ธˆ๋„ ๋ถ€์กฑํ•˜๊ธด ํ•˜์ง€๋งŒ DP๊ฐœ๋…์ด ๋ถ€์กฑํ•ด์„œ ๊ทธ๋ฆฌ๋””๋กœ ํ’€๋ ค๋‹ค๊ฐ€ ์‹คํŒจํ–ˆ๋˜ ๊ธฐ์–ต์ด ๋‚˜๋„ค์š” 

์˜ค๋žœ๋งŒ์— ์ด ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณด๊ฒŒ ๋˜์—ˆ๋Š”๋ฐ ์†์‰ฝ๊ฒŒ ํ’€๋ ค์„œ ์„ฑ์žฅํ•œ ๊ฒƒ ๊ฐ™์•„ ๊ธฐ๋ถ„์ด ์ข‹์Šต๋‹ˆ๋‹ค.

์•„๋ž˜์˜ ์ž…์ถœ๋ ฅ์œผ๋กœ ์„ค๋ช…์„ ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

land answer
[[1,2,3,5],[5,6,7,8],[4,3,2,1]] 16

 

if(k==0) dp[i][k] = max({dp[i-1][k+1],dp[i-1][k+2],dp[i-1][k+3]})+land[i][k];
if(k==1) dp[i][k] = max({dp[i-1][k-1],dp[i-1][k+1],dp[i-1][k+2]})+land[i][k];
if(k==2) dp[i][k] = max({dp[i-1][k-2],dp[i-1][k-1],dp[i-1][k+1]})+land[i][k];
if(k==3) dp[i][k] = max({dp[i-1][k-3],dp[i-1][k-2],dp[i-1][k-1]})+land[i][k];

ํ•œ ํ–‰์”ฉ ๋‚ด๋ ค์˜ค๋ฉด์„œ ๊ฐ™์€ ์—ด์€ ๋ฐŸ์„ ์ˆ˜ ์—†๋‹ค๋Š” ์ œ์•ฝ ์กฐ๊ฑด์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ณธ์ธ์˜ ์ด์ „ ์—ด์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ๋ˆ„์  ํ•ฉ ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฒƒ์„ ํ˜„์žฌ land๊ฐ’๊ณผ ๋”ํ•ด์ฃผ๊ณ , ๋งˆ์ง€๋ง‰์— ์ œ์ผ ํฐ ๊ฐ’์„ ์ถœ๋ ฅํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

๋Œ“๊ธ€