๐ŸŽฒ ๋ฐฑ์ค€ 17071๋ฒˆ ์ˆจ๋ฐ•๊ผญ์งˆ 5

Jeongeunยท2023๋…„ 11์›” 16์ผ
0

๋ฐฑ์ค€

๋ชฉ๋ก ๋ณด๊ธฐ
136/186

๋ฐฑ์ค€ 17071๋ฒˆ

๐ŸŽจ ์ฐธ๊ณ  ์ฝ”๋“œ

์ฝ”๋“œ

const fs = require('fs'); 
const [N, K] = fs.readFileSync('/dev/stdin').toString().trim().split(' ').map(Number);

const bfs = () => {
  if (N === K) return 0;
  const queue = [];
  queue.push([N, K, 0]);
  const visited = Array.from(new Array(2), () => new Array(500001).fill(-1));
  visited[0][N] = 0;

  while (queue.length) {
    let [n, k, sec] = queue.shift();

    let nextSec = sec + 1;
    let nextK = k + nextSec;

    if (nextK > 500000) return -1;

    if (n * 2 <= 500000 && visited[nextSec % 2][n * 2] === -1) {
      queue.push([n * 2, nextK, nextSec]);
      visited[nextSec % 2][n * 2] = nextSec;
    }
    if (n - 1 >= 0 && visited[nextSec % 2][n - 1] === -1) {
      queue.push([n - 1, nextK, nextSec]);
      visited[nextSec % 2][n - 1] = nextSec;
    }
    if (n + 1 <= 500000 && visited[nextSec % 2][n + 1] === -1) {
      queue.push([n + 1, nextK, nextSec]);
      visited[nextSec % 2][n + 1] = nextSec;
    }

    if (visited[nextSec % 2][nextK] !== -1) return nextSec;
  }
};

console.log(bfs());

0๊ฐœ์˜ ๋Œ“๊ธ€