Approach
Depth-first search
For Count Valid Paths in a Tree, 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
- 54 lines of C++ from the credited upstream file 2867.cpp.
- The implementation visibly relies on sequence storage.
- 4 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 long long countPaths(int n, vector<vector<int>>& edges) {4 long ans = 0;5 const vector<bool> isPrime = sieveEratosthenes(n + 1);6 vector<vector<int>> graph(n + 1);7 8 for (const vector<int>& edge : edges) {9 const int u = edge[0];10 const int v = edge[1];11 graph[u].push_back(v);12 graph[v].push_back(u);13 }14 15 dfs(graph, 1, -1, isPrime, ans);16 return ans;17 }18 19 private:20 pair<long, long> dfs(const vector<vector<int>>& graph, int u, int prev,21 const vector<bool>& isPrime, long& ans) {22 long countZeroPrimePath = !isPrime[u];23 long countOnePrimePath = isPrime[u];24 25 for (const int v : graph[u]) {26 if (v == prev)27 continue;28 const auto& [countZeroPrimeChildPath, countOnePrimeChildPath] =29 dfs(graph, v, u, isPrime, ans);30 ans += countZeroPrimePath * countOnePrimeChildPath +31 countOnePrimePath * countZeroPrimeChildPath;32 if (isPrime[u]) {33 countOnePrimePath += countZeroPrimeChildPath;34 } else {35 countZeroPrimePath += countZeroPrimeChildPath;36 countOnePrimePath += countOnePrimeChildPath;37 }38 }39 40 return {countZeroPrimePath, countOnePrimePath};41 }42 43 vector<bool> sieveEratosthenes(int n) {44 vector<bool> isPrime(n, true);45 isPrime[0] = false;46 isPrime[1] = false;47 for (int i = 2; i * i < n; ++i)48 if (isPrime[i])49 for (int j = i * i; j < n; j += i)50 isPrime[j] = false;51 return isPrime;52 }53};54