Approach
Depth-first search
For Minimum Weighted Subgraph With the Required Paths II, 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
- 85 lines of C++ from the credited upstream file 3553.cpp.
- The implementation visibly relies on sequence storage.
- 7 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:3 4 vector<int> minimumWeight(vector<vector<int>>& edges,5 vector<vector<int>>& queries) {6 const int n = edges.size() + 1;7 const int m = ceil(log2(n));8 vector<int> ans;9 vector<vector<pair<int, int>>> graph(n);10 11 vector<vector<int>> jump(n, vector<int>(m));12 13 vector<int> depth(n);14 15 vector<int> dist(n);16 17 for (const vector<int>& edge : edges) {18 const int u = edge[0];19 const int v = edge[1];20 const int w = edge[2];21 graph[u].emplace_back(v, w);22 graph[v].emplace_back(u, w);23 }24 25 dfs(graph, 0, -1, jump, depth, dist);26 27 for (int j = 1; j < m; ++j)28 for (int i = 0; i < n; ++i)29 jump[i][j] = jump[jump[i][j - 1]][j - 1];30 31 for (const vector<int>& query : queries) {32 const int src1 = query[0];33 const int src2 = query[1];34 const int dest = query[2];35 ans.push_back((distance(src1, src2, jump, depth, dist) +36 distance(src1, dest, jump, depth, dist) +37 distance(src2, dest, jump, depth, dist)) /38 2);39 }40 41 return ans;42 }43 44 private:45 void dfs(const vector<vector<pair<int, int>>>& graph, int u, int prev,46 vector<vector<int>>& jump, vector<int>& depth, vector<int>& dist) {47 for (const auto& [v, w] : graph[u]) {48 if (v == prev)49 continue;50 jump[v][0] = u;51 depth[v] = depth[u] + 1;52 dist[v] = dist[u] + w;53 dfs(graph, v, u, jump, depth, dist);54 }55 }56 57 58 int getLCA(int u, int v, const vector<vector<int>>& jump,59 const vector<int>& depth) {60 61 if (depth[u] > depth[v])62 return getLCA(v, u, jump, depth);63 64 for (int j = 0; j < jump[0].size(); ++j)65 if (depth[v] - depth[u] >> j & 1)66 v = jump[v][j];67 if (u == v)68 return u;69 70 for (int j = jump[0].size() - 1; j >= 0; --j)71 if (jump[u][j] != jump[v][j]) {72 u = jump[u][j];73 v = jump[v][j];74 }75 return jump[u][0];76 }77 78 79 int distance(int u, int v, const vector<vector<int>>& jump,80 const vector<int>& depth, const vector<int>& dist) {81 const int lca = getLCA(u, v, jump, depth);82 return dist[u] + dist[v] - 2 * dist[lca];83 }84};85