Approach
Depth-first search
For Time Taken to Mark All Nodes, 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
- 83 lines of C++ from the credited upstream file 3241.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 3 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.
1struct Node {2 int node = 0; 3 int time = 0; 4};5 6struct Top2 {7 8 9 Node top1;10 11 12 Node top2;13};14 15class Solution {16 public:17 vector<int> timeTaken(vector<vector<int>>& edges) {18 const int n = edges.size() + 1;19 vector<int> ans(n);20 vector<vector<int>> tree(n);21 22 23 24 vector<Top2> dp(n);25 26 for (const vector<int>& edge : edges) {27 const int u = edge[0];28 const int v = edge[1];29 tree[u].push_back(v);30 tree[v].push_back(u);31 }32 33 dfs(tree, 0, -1, dp);34 reroot(tree, 0, -1, 0, dp, ans);35 return ans;36 }37 38 private:39 40 int getTime(int u) {41 return u % 2 == 0 ? 2 : 1;42 }43 44 45 46 47 48 49 50 int dfs(const vector<vector<int>>& tree, int u, int prev, vector<Top2>& dp) {51 Node top1;52 Node top2;53 for (const int v : tree[u]) {54 if (v == prev)55 continue;56 const int time = dfs(tree, v, u, dp) + getTime(v);57 if (time >= top1.time) {58 top2 = top1;59 top1 = Node(v, time);60 } else if (time > top2.time) {61 top2 = Node(v, time);62 }63 }64 dp[u] = Top2(top1, top2);65 return top1.time;66 }67 68 69 70 void reroot(const vector<vector<int>>& tree, int u, int prev, int maxTime,71 const vector<Top2>& dp, vector<int>& ans) {72 ans[u] = max(maxTime, dp[u].top1.time);73 for (const int v : tree[u]) {74 if (v == prev)75 continue;76 const int newMaxTime =77 getTime(u) + max(maxTime, dp[u].top1.node == v ? dp[u].top2.time78 : dp[u].top1.time);79 reroot(tree, v, u, newMaxTime, dp, ans);80 }81 }82};83