✔ Problem - [15729] 방탈출 - DP

🔰 Level

  • solved.ac 기준 실버1

❔ How

  • dynamic programming 문제이다.
  • 내가 버튼을 누른 횟수를 출력하면 된다.
  • 앞에서부터 정답과 나의 빈 답지를 비교하며, 눌러 나간다.
  • 먼저 정답 버튼과 길이가 같은 0으로 채워진 새로운 배열을 만들고, 정답과 비교하면서 버튼을 누를 때마다 오른쪽 2개의 버튼도 갱신해주면서 하나씩 눌러나가면 된다.

✅ Source Code

const inputs = require('fs')
    .readFileSync(
        process.platform === 'linux' ? 'dev/stdin' : 'input.txt'
    )
    .toString()
    .trim()
    .split('\n');

const n = +inputs[0];
const arr = inputs[1].split(' ').map(Number);
let pwd = new Array(n).fill(0);
let cnt = 0;

for (let i = 0; i < n; i++) {
    if (arr[i] !== pwd[i]) { //답이랑 다른 상태면
        cnt += 1;
        pwd[i] = pwd[i] === 0 ? 1 : 0; //0인건 1로, 1인건 0으로 눌러주고
        if (i < n - 1) {
            pwd[i + 1] = pwd[i + 1] === 0 ? 1 : 0; //옆의 것도 바꿔줘야함.
            if (i < n) { pwd[i + 2] = pwd[i + 2] === 0 ? 1 : 0 }; //옆의 것도 바꿔줘야함.
        }
    }
}

console.log(cnt);
profile
wanna be bright person✨ Front-End developer

0개의 댓글