ericagong / algorithm_solving

2 stars 0 forks source link

[이진탐색] 랜선 자르기 #96

Open ericagong opened 1 year ago

ericagong commented 1 year ago

⭐ 성찰

  1. 시작 인덱스가 항상 0인 것이 아님. 문제 조건 잘 읽기 랜선의 길이는 231-1보다 작거나 같은 자연수

❓ 문제 상황

랜선 자르기

👨‍💻 문제 해결: 이진 탐색

✅ 1차 풀이: 간단한 이진 탐색

const fs = require('fs')
const inputs = fs.readFileSync('/dev/stdin').toString().split('\n')

const [K, N] = inputs.shift().split(' ').map(Number)
const lines = []
for(let i = 0; i < K; i++) {
  lines.push(Number(inputs.shift()))
}
const maxLine = Math.max(...lines)

let len = 0
function binarySearch(s, e) {
  while(s <= e) {
    const m = parseInt((s + e) / 2)

    let cnt = 0
    lines.forEach((line) => {
      cnt += parseInt(line / m)
    })

    if(cnt >= N) {
      len = m
      s = m + 1
    }
    else e = m - 1
  }
}

// 0부터 시작하면 안됨
binarySearch(1, maxLine)
console.log(len)