You are viewing a single comment's thread. Return to all comments →
Java O(n+m)
public static long roadsAndLibraries(int n, int c_lib, int c_road, List<List<Integer>> cities) { if (c_lib <= c_road) { return (long) n * c_lib; } List<List<Integer>> adjList = new ArrayList<>(); for (int i = 0; i <= n; i++) { adjList.add(new ArrayList<>()); } for (List<Integer> city : cities) { int u = city.get(0); int v = city.get(1); adjList.get(u).add(v); adjList.get(v).add(u); } boolean[] visited = new boolean[n + 1]; long totalCost = 0; for (int i = 1; i <= n; i++) { if (!visited[i]) { long componentSize = dfs(i, adjList, visited); totalCost += c_lib + (componentSize - 1) * c_road; } } return totalCost; } private static long dfs(int node, List<List<Integer>> adjList, boolean[] visited) { Stack<Integer> stack = new Stack<>(); stack.push(node); visited[node] = true; long size = 0; while (!stack.isEmpty()) { int current = stack.pop(); size++; for (int neighbor : adjList.get(current)) { if (!visited[neighbor]) { visited[neighbor] = true; stack.push(neighbor); } } } return size; }
Seems like cookies are disabled on this browser, please enable them to open this website
Roads and Libraries
You are viewing a single comment's thread. Return to all comments →
Java O(n+m)