[백준 2240번] DP(다이나믹 프로그래밍) - 자두나무

김민지·2023년 8월 23일
0

냅다 시작 백준

목록 보기
81/118

✨ 문제 ✨

✨ 정답 ✨


const { count } = require("console");
const fs = require("fs");
const { nextTick } = require("process");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./예제.txt";
let input = fs.readFileSync(filePath).toString().trim();


// const fs = require('fs'); 
// let input = fs.readFileSync("/dev/stdin").toString().trim();

input = input.split('\n')
const [T, W] = input[0].split(' ').map((el) => +el)
let dp = Array.from({ length: T+1 }, () =>new Array(W+1).fill(0))
let answer=0;

for (let i=1;i<T+1;i++){
    // 아래 이걸 해줘야 하더라...?
    // dp 콘솔에 찍어봐서 알게됨.
    let tree=+input[i];
    for (let j=0;j<=W;j++){
        if (j===0){
            if (tree===1){
                dp[i][j]=dp[i-1][j]+1;
            }else{
                dp[i][j]=dp[i-1][j];
            }
            continue;
        }
        if (j%2===0){
            if (tree===1){

                dp[i][j]=Math.max(dp[i-1][j-1], dp[i-1][j]+1);
            }else{
        
                dp[i][j]=Math.max(dp[i-1][j-1]+1, dp[i-1][j]);
            }
        }else{
            if (tree===1){

                dp[i][j]=Math.max(dp[i-1][j-1]+1, dp[i-1][j]);
            }else{
                
                dp[i][j]=Math.max(dp[i-1][j-1], dp[i-1][j]+1);
            }
        }
    }
    for (let m=0;m<=W;m++){
        answer=Math.max(answer, dp[T][m]);
    }

}

console.log(answer)

🧵 참고한 정답지 🧵

💡💡 기억해야 할 점 💡💡

3차원짜리 dp도 있다.
다중 for문 사용할 때 인덱스 변수 헷갈리지 말자...

profile
이건 대체 어떻게 만든 거지?

0개의 댓글