๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐Ÿ–ฅ dev-ruby

[๋ฐฑ์ค€][๋ธŒ๋ฃจํŠธํฌ์Šค]์น˜ํ‚จ ๋ฐฐ๋‹ฌ - node.js | javascript | gold5 ๋ณธ๋ฌธ

๋ฐฑ์ค€

[๋ฐฑ์ค€][๋ธŒ๋ฃจํŠธํฌ์Šค]์น˜ํ‚จ ๋ฐฐ๋‹ฌ - node.js | javascript | gold5

ruby_s 2022. 4. 28. 09:46
728x90
๋ฐ˜์‘ํ˜•
SMALL

๋ฌธ์ œ

https://www.acmicpc.net/problem/15686

 

15686๋ฒˆ: ์น˜ํ‚จ ๋ฐฐ๋‹ฌ

ํฌ๊ธฐ๊ฐ€ N×N์ธ ๋„์‹œ๊ฐ€ ์žˆ๋‹ค. ๋„์‹œ๋Š” 1×1ํฌ๊ธฐ์˜ ์นธ์œผ๋กœ ๋‚˜๋ˆ„์–ด์ ธ ์žˆ๋‹ค. ๋„์‹œ์˜ ๊ฐ ์นธ์€ ๋นˆ ์นธ, ์น˜ํ‚จ์ง‘, ์ง‘ ์ค‘ ํ•˜๋‚˜์ด๋‹ค. ๋„์‹œ์˜ ์นธ์€ (r, c)์™€ ๊ฐ™์€ ํ˜•ํƒœ๋กœ ๋‚˜ํƒ€๋‚ด๊ณ , rํ–‰ c์—ด ๋˜๋Š” ์œ„์—์„œ๋ถ€ํ„ฐ r๋ฒˆ์งธ ์นธ

www.acmicpc.net

 

ํ’€์ด

function solve() {
  const twoIdxList = [],
    oneIdxList = [];
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      if (city[i][j] === 2) twoIdxList.push([i, j]);
      else if (city[i][j] === 1) oneIdxList.push([i, j]);
    }
  }

  function getCombination(arr, num) {
    const result = [];
    if (num === 1) return arr.map((el) => [el]);

    arr.forEach((fixed, index, origin) => {
      const rest = origin.slice(index + 1);
      const combination = getCombination(rest, num - 1);
      const attached = combination.map((el) => [fixed, ...el]);
      result.push(...attached);
    });
    return result;
  }

  function getMinDistance(chickenIdx) {
    let sum = 0;
    for (const [oneX, oneY] of oneIdxList) {
      let distance = Infinity;
      for (const [twoX, twoY] of chickenIdx) {
        distance = Math.min(
          distance,
          Math.abs(oneX - twoX) + Math.abs(oneY - twoY)
        );
      }
      sum += distance;
    }
    return sum;
  }

  const combination = getCombination(twoIdxList, m);

  let answer = Infinity;
  for (const indexs of combination) {
    answer = Math.min(answer, getMinDistance(indexs));
  }
  return answer;
}

const filePath =
  process.platform === "linux" ? "/dev/stdin" : "๋ฐฑ์ค€/gold/15686/testcase.txt";
const input = require("fs")
  .readFileSync(filePath)
  .toString()
  .trim()
  .split("\n")
  .map((row) => row.split(" ").map((el) => +el));
const [n, m] = input[0];
const city = input.slice(1);
console.log(solve());

์ด ๋ฌธ์ œ๋Š” ์กฐํ•ฉ๋งŒ ์“ฐ๋ฉด ์‰ฝ๊ฒŒ ํ‘ธ๋Š” ๋ฌธ์ œ๋‹ค.
์กฐํ•ฉ์œผ๋กœ ์น˜ํ‚จ ์ง‘(2) ์ค‘ ํ์—… ์‹œํ‚ค์ง€ ์•Š์„ ์ธ๋ฑ์Šค ์กฐํ•ฉ๋“ค์„ ๋งŒ๋“ค๊ณ , ์ง‘(1)์—์„œ๋ถ€ํ„ฐ ์น˜ํ‚จ ์ง‘๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์ญ‰ ๋ฐ˜๋ณต๋ฌธ ๋Œ๋ ค์„œ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค.

Math.min ์œผ๋กœ ๊ณ„์†ํ•ด์„œ ์ตœ์†Œ๊ฐ’์„ ๋ฐ˜์˜ํ•ด์ฃผ๋ฉด ํ’€์ด ๋ !

 

์ข€ ๋” ์‰ฌ์šด ํ’€์ด๋ฅผ ์•„์‹œ๊ฑฐ๋‚˜ ๊ณ ์ณ์•ผ ํ•  ์ฝ”๋“œ๊ฐ€ ์žˆ๋‹ค๋ฉด ๋Œ“๊ธ€๋กœ ์•Œ๋ ค์ฃผ์„ธ์š” ! ๐Ÿ˜€

 

728x90
๋ฐ˜์‘ํ˜•
LIST