• + 0 comments

    The shortest solution I was able to create:

    def roadsAndLibraries(n, c_lib, c_road, cities):
        # Write your code here
        if c_road>c_lib:
            return n*c_lib
        conns = defaultdict(set)
        for i in range(n):
            conns[i+1]=set()
        for i in range(len(cities)):
            conns[cities[i-1][0]].add(cities[i-1][1])
            conns[cities[i-1][1]].add(cities[i-1][0])
        conns = dict(sorted(conns.items(), key=lambda item: -len(item[1])))
        lens = []
        for c in conns:
            lens.append(len(conns[c]))
            
        unvisited=set(range(1,n+1))
        cost=0
        while unvisited:
            current = unvisited.pop()
            cost+=c_lib
            connected = set(conns[current])
            while (connected):
                nb = connected.pop()
                if nb in unvisited:
                    unvisited.remove(nb)
                    for i in conns[nb]:
                        connected.add(i)
                    cost+=c_road
        return cost
    
                co
    return cost