Approach
Depth-first search
For Longest Special Path, 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
- 50 lines of C++ from the credited upstream file 3425.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 2 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 vector<int> longestSpecialPath(vector<vector<int>>& edges,4 vector<int>& nums) {5 vector<vector<pair<int, int>>> graph(nums.size());6 7 for (const vector<int>& edge : edges) {8 const int u = edge[0];9 const int v = edge[1];10 const int w = edge[2];11 graph[u].emplace_back(v, w);12 graph[v].emplace_back(u, w);13 }14 15 int maxLength = 0;16 int minNodes = 1;17 dfs(graph, 0, -1, 0, {0},18 {}, nums, maxLength, minNodes);19 return {maxLength, minNodes};20 }21 22 private:23 void dfs(const vector<vector<pair<int, int>>>& graph, int u, int prev,24 int leftBoundary, vector<int>&& prefix,25 unordered_map<int, int>&& lastSeenDepth, const vector<int>& nums,26 int& maxLength, int& minNodes) {27 const int prevDepth = lastSeenDepth[nums[u]];28 lastSeenDepth[nums[u]] = prefix.size();29 leftBoundary = max(leftBoundary, prevDepth);30 31 const int length = prefix.back() - prefix[leftBoundary];32 const int nodes = prefix.size() - leftBoundary;33 if (length > maxLength || (length == maxLength && nodes < minNodes)) {34 maxLength = length;35 minNodes = nodes;36 }37 38 for (const auto& [v, w] : graph[u]) {39 if (v == prev)40 continue;41 prefix.push_back(prefix.back() + w);42 dfs(graph, v, u, leftBoundary, std::move(prefix),43 std::move(lastSeenDepth), nums, maxLength, minNodes);44 prefix.pop_back();45 }46 47 lastSeenDepth[nums[u]] = prevDepth;48 }49};50