Approach
Depth-first search
For Finish Time of Tasks I, 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
- 68 lines of C++ from the credited upstream file finish-time-of-tasks-i.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 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.
123 45class Solution {6public:7 long long finishTime(int n, vector<vector<int>>& edges, vector<int>& baseTime) {8 static const auto& POS_INF = numeric_limits<int64_t>::max();9 static const auto& NEG_INF = numeric_limits<int64_t>::min();10 11 vector<vector<int>> adj(n);12 const auto iter_dfs = [&]() {13 vector<int64_t> dp(n);14 vector<pair<int, int>> stk = {{1, 0}};15 while (!empty(stk)) {16 const auto [step, u] = stk.back(); stk.pop_back();17 if (step == 1) {18 stk.emplace_back(2, u);19 for (const auto& v : adj[u]) {20 stk.emplace_back(1, v);21 }22 } else if (step == 2) {23 auto mx = numeric_limits<int64_t>::min();24 auto mn = numeric_limits<int64_t>::max();25 for (const auto& v : adj[u]) {26 mx = max(mx, dp[v]);27 mn = min(mn, dp[v]);28 }29 dp[u] = (mx != NEG_INF ? (2 * mx - mn) : 0) + baseTime[u];30 }31 }32 return dp[0];33 };34 35 for (const auto& e : edges) {36 adj[e[0]].emplace_back(e[1]);37 }38 return iter_dfs();39 }40};41 42434445class Solution2 {46public:47 long long finishTime(int n, vector<vector<int>>& edges, vector<int>& baseTime) {48 static const auto& POS_INF = numeric_limits<int64_t>::max();49 static const auto& NEG_INF = numeric_limits<int64_t>::min();50 51 vector<vector<int>> adj(n);52 const auto dfs = [&](this auto&& dfs, int u) -> int64_t {53 auto mx = NEG_INF, mn = POS_INF;54 for (const auto& v : adj[u]) {55 const auto& ret = dfs(v);56 mx = max(mx, ret);57 mn = min(mn, ret);58 }59 return (mx != NEG_INF ? (2 * mx - mn) : 0) + baseTime[u];60 };61 62 for (const auto& e : edges) {63 adj[e[0]].emplace_back(e[1]);64 }65 return dfs(0);66 }67};68