Approach
Depth-first search
For Minimum Edge Weight Equilibrium Queries in a Tree, 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
- 81 lines of Java from the credited upstream file 2846.java.
- The implementation visibly relies on sequence storage.
- 8 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[] minOperationsQueries(int n, int[][] edges, int[][] queries) {3 final int MAX = 26;4 final int m = (int) Math.ceil(Math.log(n) / Math.log(2));5 int[] ans = new int[queries.length];6 List<Pair<Integer, Integer>>[] graph = new List[n];7 8 int[][] jump = new int[n][m];9 10 int[] depth = new int[n];11 12 int[][] count = new int[n][MAX + 1];13 Arrays.setAll(graph, i -> new ArrayList<>());14 15 for (int[] edge : edges) {16 final int u = edge[0];17 final int v = edge[1];18 final int w = edge[2];19 graph[u].add(new Pair<>(v, w));20 graph[v].add(new Pair<>(u, w));21 }22 23 count[0] = new int[MAX + 1];24 dfs(graph, 0, -1, jump, depth, count);25 26 for (int j = 1; j < m; ++j)27 for (int i = 0; i < n; ++i)28 jump[i][j] = jump[jump[i][j - 1]][j - 1];29 30 for (int i = 0; i < queries.length; ++i) {31 final int u = queries[i][0];32 final int v = queries[i][1];33 final int lca = getLCA(u, v, jump, depth);34 35 final int numEdges = depth[u] + depth[v] - 2 * depth[lca];36 37 int maxFreq = 0;38 for (int j = 1; j <= MAX; ++j)39 maxFreq = Math.max(maxFreq, count[u][j] + count[v][j] - 2 * count[lca][j]);40 ans[i] = numEdges - maxFreq;41 }42 43 return ans;44 }45 46 private void dfs(List<Pair<Integer, Integer>>[] graph, int u, int prev, int[][] jump, int[] depth,47 int[][] count) {48 for (Pair<Integer, Integer> pair : graph[u]) {49 final int v = pair.getKey();50 final int w = pair.getValue();51 if (v == prev)52 continue;53 jump[v][0] = u;54 depth[v] = depth[u] + 1;55 count[v] = count[u].clone();56 ++count[v][w];57 dfs(graph, v, u, jump, depth, count);58 }59 }60 61 62 private int getLCA(int u, int v, int[][] jump, int[] depth) {63 64 if (depth[u] > depth[v])65 return getLCA(v, u, jump, depth);66 67 for (int j = 0; j < jump[0].length; ++j)68 if ((depth[v] - depth[u] >> j & 1) == 1)69 v = jump[v][j];70 if (u == v)71 return u;72 73 for (int j = jump[0].length - 1; j >= 0; --j)74 if (jump[u][j] != jump[v][j]) {75 u = jump[u][j];76 v = jump[v][j];77 }78 return jump[v][0];79 }80}81