모든 Field를 최소 비용으로 연결하라는 점에서 MST를 떠올렸습니다. MST를 구하는 알고리즘 중 간선 중심인 Kruskal 알고리즘을 사용하여 풀었습니다.
이 문제에서 메모리 초과, 시간 초과를 모두 겪었습니다.
이러한 개선을 하여 정답을 맞췄습니다.
const fs = require('fs')
const filePath = process.platform === 'linux' ? 'dev/stdin' : './input.txt'
const input = fs
.readFileSync(filePath)
.toString()
.trim()
.split('\n')
.map((el) => el.split(' ').map(Number))
function find(a) {
if (parent[a] === a) return a
else return (parent[a] = find(parent[a]))
}
function union(a, b) {
a = find(a)
b = find(b)
if (a === b) return false
if (a < b) parent[b] = a
else parent[a] = b
return true
}
const [N, C] = input.shift()
const pq = []
const parent = Array(N)
for (let i = 0; i < N; i++) parent[i] = i
// 간선 추가
for (let i = 0; i < N - 1; i++) {
for (let j = i + 1; j < N; j++) {
const distance =
Math.pow(Math.abs(input[i][0] - input[j][0]), 2) +
Math.pow(Math.abs(input[i][1] - input[j][1]), 2)
if (distance >= C) {
pq.push({ from: i, to: j, weight: distance })
}
}
}
pq.sort((a, b) => b.weight - a.weight)
let result = 0,
cnt = 0
while (pq.length > 0) {
const temp = pq.pop()
if (union(temp.from, temp.to)) {
result += temp.weight
cnt += 1
if (cnt === N - 1) break
}
}
if (cnt === N - 1) console.log(result)
else console.log(-1)