Approach
Depth-first search
For Minimize the Total Price of the Trips, 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
- 67 lines of C++ from the credited upstream file 2646.cpp.
- The implementation visibly relies on sequence storage.
- 6 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 int minimumTotalPrice(int n, vector<vector<int>>& edges, vector<int>& price,4 vector<vector<int>>& trips) {5 vector<vector<int>> graph(n);6 7 for (const vector<int>& edge : edges) {8 const int u = edge[0];9 const int v = edge[1];10 graph[u].push_back(v);11 graph[v].push_back(u);12 }13 14 15 vector<int> count(n);16 17 for (const vector<int>& trip : trips) {18 const int start = trip[0];19 const int end = trip[1];20 vector<int> path;21 dfsCount(graph, start, -1, end, count, path);22 }23 24 vector<vector<int>> mem(n, vector<int>(2, -1));25 return dfs(graph, 0, -1, price, count, false, mem);26 }27 28 private:29 void dfsCount(const vector<vector<int>>& graph, int u, int prev, int end,30 vector<int>& count, vector<int>& path) {31 path.push_back(u);32 if (u == end) {33 for (const int i : path)34 ++count[i];35 return;36 }37 for (const int v : graph[u])38 if (v != prev)39 dfsCount(graph, v, u, end, count, path);40 path.pop_back();41 }42 43 44 45 int dfs(const vector<vector<int>>& graph, int u, int prev,46 const vector<int>& price, const vector<int>& count, int parentHalved,47 vector<vector<int>>& mem) {48 if (mem[u][parentHalved] != -1)49 return mem[u][parentHalved];50 51 int sumWithFullNode = price[u] * count[u];52 for (const int v : graph[u])53 if (v != prev)54 sumWithFullNode += dfs(graph, v, u, price, count, false, mem);55 56 if (parentHalved) 57 return mem[u][parentHalved] = sumWithFullNode;58 59 int sumWithHalvedNode = (price[u] / 2) * count[u];60 for (const int v : graph[u])61 if (v != prev)62 sumWithHalvedNode += dfs(graph, v, u, price, count, true, mem);63 64 return mem[u][parentHalved] = min(sumWithFullNode, sumWithHalvedNode);65 }66};67