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
- 94 lines of Python from the credited upstream file 3241.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit 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.
1from dataclasses import dataclass2 3 4@dataclass5class Node:6 node: int = 0 7 time: int = 0 8 9 10class Top2:11 def __init__(self, top1: Node = Node(), top2: Node = Node()):12 13 14 self.top1 = top115 16 17 self.top2 = top218 19 20class Solution:21 def timeTaken(self, edges: list[list[int]]) -> list[int]:22 n = len(edges) + 123 ans = [0] * n24 tree = [[] for _ in range(n)]25 26 27 28 dp = [Top2()] * n29 30 for u, v in edges:31 tree[u].append(v)32 tree[v].append(u)33 34 self._dfs(tree, 0, -1, dp)35 self._reroot(tree, 0, -1, 0, dp, ans)36 return ans37 38 def _getTime(self, u: int) -> int:39 """Returns the time taken to mark node u."""40 return 2 if u % 2 == 0 else 141 42 def _dfs(43 self,44 tree: list[list[int]],45 u: int,46 prev: int,47 dp: list[Top2]48 ) -> int:49 """50 Performs a DFS traversal of the subtree rooted at node `u`, computes the51 time taken to mark all nodes in the subtree, records the top two direct52 child nodes, where the time taken to mark the subtree rooted at each of the53 child nodes is maximized, and returns the top child node.54 55 These values are used later in the rerooting process.56 """57 top1 = Node()58 top2 = Node()59 for v in tree[u]:60 if v == prev:61 continue62 time = self._dfs(tree, v, u, dp) + self._getTime(v)63 if time >= top1.time:64 top2 = top165 top1 = Node(v, time)66 elif time > top2.time:67 top2 = Node(v, time)68 dp[u] = Top2(top1, top2)69 return top1.time70 71 def _reroot(72 self,73 tree: list[list[int]],74 u: int,75 prev: int,76 maxTime: int,77 dp: list[Top2],78 ans: list[int]79 ) -> None:80 """81 Reroots the tree at node `u` and updates the answer array, where `maxTime`82 is the longest path that doesn't go through `u`'s subtree.83 """84 ans[u] = max(maxTime, dp[u].top1.time)85 86 for v in tree[u]:87 if v == prev:88 continue89 newMaxTime = self._getTime(u) + max(90 maxTime,91 dp[u].top2.time if dp[u].top1.node == v else dp[u].top1.time92 )93 self._reroot(tree, v, u, newMaxTime, dp, ans)94