Roads and Libraries

  • + 0 comments

    Solution in Java, quick and simple

    public static long roadsAndLibraries(int n, int c_lib, int c_road, List<List<Integer>> cities) {
            if(cities.isEmpty() || c_lib <= c_road) return 1L * n * c_lib;
            
            TreeMap<Integer, Stack<Integer>> cityMap = new TreeMap<>();
            for(List<Integer> connection: cities){
                int c1 = connection.get(0), c2 = connection.get(1);
                cityMap.computeIfAbsent(c1, k -> new Stack<>()).add(c2);
                cityMap.computeIfAbsent(c2, k -> new Stack<>()).add(c1);
            }
            
            long libs = n - cityMap.size(), roads = 0L;
            
            while(!cityMap.isEmpty()){
                // Start new cycle
                libs++;
                Stack<Integer> stack = cityMap.pollFirstEntry().getValue();
                while(!stack.isEmpty()) {
                    // DFS for connected cities
                    int c = stack.pop();
                    if(cityMap.containsKey(c)){
                        roads++;
                        stack.addAll(cityMap.remove(c));
                    }
                }
            }
            
            return libs * c_lib + roads * c_road;
        }