Roads and Libraries

  • + 0 comments

    JavaScript

    function roadsAndLibraries(n, c_lib, c_road, cities) {
        // Write your code here
        if (c_road >= c_lib) return n * c_lib
        
        let arr = []
        for (let i = 1; i <= n; i++) arr[i] = [i]
        for (let i = 0; i < cities.length; i++) {
            let [m, n] = cities[i]
            if (arr[m] === arr[n]) continue
            if (arr[m].length < arr[n].length) [m, n] = [n, m]
            for (let temp of arr[n]) arr[m].push(temp), arr[temp] = arr[m]
        }
        let groups = new Set()
        for (let temp of arr.slice(1)) groups.add(temp)
        let cost = groups.size * c_lib + Array.from(groups).map(group => group.length - 1).reduce((acc, cur) => acc + cur * c_road, 0)
        return cost
    }