Approach
Breadth-first search
For Collect Coins in a Tree, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 51 lines of C++ from the credited upstream file 2603.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
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 collectTheCoins(vector<int>& coins, vector<vector<int>>& edges) {4 const int n = coins.size();5 vector<unordered_set<int>> tree(n);6 queue<int> leavesToBeRemoved;7 8 for (const vector<int>& edge : edges) {9 const int u = edge[0];10 const int v = edge[1];11 tree[u].insert(v);12 tree[v].insert(u);13 }14 15 for (int i = 0; i < n; ++i) {16 int u = i;17 18 while (tree[u].size() == 1 && coins[u] == 0) {19 const int v = *tree[u].begin();20 tree[u].clear();21 tree[v].erase(u);22 u = v; 23 }24 25 26 if (tree[u].size() == 1)27 leavesToBeRemoved.push(u);28 }29 30 31 32 for (int i = 0; i < 2; ++i)33 for (int sz = leavesToBeRemoved.size(); sz > 0; --sz) {34 const int u = leavesToBeRemoved.front();35 leavesToBeRemoved.pop();36 if (!tree[u].empty()) {37 const int v = *tree[u].begin();38 tree[u].clear();39 tree[v].erase(u);40 if (tree[v].size() == 1)41 leavesToBeRemoved.push(v);42 }43 }44 45 return accumulate(tree.begin(), tree.end(), 0,46 [](int acc, const unordered_set<int>& children) {47 return acc + children.size();48 });49 }50};51