• + 0 comments

    Greetings! I wonder if anyone could help me figure out why I get failed tests, my approach is simply to count subgraphs, which should be enough to calculate least possible cost. Thanks!

    public static long roadsAndLibraries(int n, int c_lib, int c_road, List<List<Integer>> cities) {
            if(c_lib <= c_road || cities == null || cities.size() == 0)
                return c_lib * n;
            
            List<List<Integer>> adj = new ArrayList<>(n);
            for(int i = 0; i < n; i++){
                adj.add(new ArrayList<>());
            }
            for(int i = 0; i < cities.size(); i++){
                int u = cities.get(i).get(0) - 1;
                int v = cities.get(i).get(1) - 1;
                adj.get(u).add(v);
                adj.get(v).add(u);
            }
            boolean[] visited = new boolean[n];
            long clusters = 0;
            for(int i = 0; i < n; i++){
                if(visited[i]) continue;
                clusters++;
                Queue<Integer> subGraph = new LinkedList<>();
                subGraph.offer(i);
                while(!subGraph.isEmpty()){
                    int curr = subGraph.poll();
                    if(visited[curr]) continue;
                    visited[curr] = true;
                    //subGraph.addAll(adj.get(curr));
                    for(Integer next : adj.get(curr)) {
                        if(!visited[next]) subGraph.add(next);
                    }
                }
            }
    
            return (long)(clusters * c_lib) + (long)(n - clusters) * c_road;
        }