[백준/node.js] 1654번 랜선 자르기 (왜 안될까..?)

2023. 9. 25. 11:26Trip to Cote

const input = require("fs")
  .readFileSync("/dev/stdin")
  .toString()
  .replaceAll("\r", "")
  .split("\n");

const n = input[0].split(" ").map(Number)[0];
const k = input[0].split(" ").map(Number)[1];
const arr = [...input].slice(1).map(Number);

let start = 1;
let end = arr.sort()[arr.length - 1];
let result = 0;

while (start <= end) {
  let mid = Math.floor((start + end) / 2);
  let total = arr
    .map((line) => parseInt(line / mid))
    .reduce((a, b) => a + b, 0);

  if (total < k) {
    end = mid - 1;
  } else if (total >= k) {
    result = mid;
    start = mid + 1;
  }
}

console.log(result);

이 식을 제출했는데 통과를 못했다. 그런데 인터넷에서 답을 찾아보니 변반 차이가 없는데 통과를 했다.

 

const input = require("fs").readFileSync('example.txt').toString().trim().split('\n');

const [n, k] = input.shift().split(' ').map((a) => +a);


	const lines = input.map((a) => +a).sort();
	let max = Math.max(...lines);
	let min = 1;

while (min <= max) {
  let mid = parseInt((max + min) / 2);
  let howManyPieces = lines
    .map((line) => parseInt(line / mid))
    .reduce((a, b) => a + b, 0);
  if (howManyPieces >= k) {
    min = mid + 1;
  } else {
    max = mid - 1;
  }
}
console.log(max);

이유를 모르겠다..