Approach
Depth-first search
For Count Pairs of Connectable Servers in a Weighted Tree Network, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 54 lines of Java from the credited upstream file 3067.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] countPairsOfConnectableServers(int[][] edges, int signalSpeed) {3 final int n = edges.length + 1;4 int[] ans = new int[n];5 List<Pair<Integer, Integer>>[] graph = new List[n];6 7 for (int i = 0; i < n; i++)8 graph[i] = new ArrayList<>();9 10 for (final int[] edge : edges) {11 final int u = edge[0];12 final int v = edge[1];13 final int w = edge[2];14 graph[u].add(new Pair<>(v, w));15 graph[v].add(new Pair<>(u, w));16 }17 18 for (int i = 0; i < n; ++i)19 ans[i] = connectablePairsRootedAt(graph, i, signalSpeed);20 21 return ans;22 }23 24 25 26 private int connectablePairsRootedAt(List<Pair<Integer, Integer>>[] graph, int u,27 int signalSpeed) {28 int pairs = 0;29 int count = 0;30 for (Pair<Integer, Integer> pair : graph[u]) {31 final int v = pair.getKey();32 final int w = pair.getValue();33 final int childCount = dfs(graph, v, u, w, signalSpeed);34 pairs += count * childCount;35 count += childCount;36 }37 return pairs;38 }39 40 41 42 private int dfs(List<Pair<Integer, Integer>>[] graph, int u, int prev, int dist,43 int signalSpeed) {44 int count = 0;45 for (Pair<Integer, Integer> pair : graph[u]) {46 final int v = pair.getKey();47 final int w = pair.getValue();48 if (v != prev)49 count += dfs(graph, v, u, dist + w, signalSpeed);50 }51 return (dist % signalSpeed == 0 ? 1 : 0) + count;52 }53}54