question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
count-valid-paths-in-a-tree
Video Explanation [Complete Brute Force --> DSU journey - O(N)]
video-explanation-complete-brute-force-d-q84x
Explanation\n\nClick here for the video\n\n# Code\n\nstruct DSU {\n vector<int> par;\n vector<int> cnt;\n \n DSU (int n) {\n par.resize(n+1,
codingmohan
NORMAL
2023-09-24T04:50:41.949463+00:00
2023-09-24T04:50:41.949483+00:00
890
false
# Explanation\n\n[Click here for the video](https://youtu.be/8XVSfMU-Y68)\n\n# Code\n```\nstruct DSU {\n vector<int> par;\n vector<int> cnt;\n \n DSU (int n) {\n par.resize(n+1, 0);\n cnt.resize(n+1, 1);\n \n for (int j = 0; j <= n; j ++) par[j] = j;\n }\n \n int Leader (int x) {\n if (x == par[x]) return x;\n return (par[x] = Leader(par[x]));\n }\n \n void Merge (int x, int y) {\n x = Leader(x);\n y = Leader(y);\n \n if (x == y) return;\n if (cnt[x] > cnt[y]) swap(x, y);\n \n cnt[y] += cnt[x];\n par[x] = y;\n }\n};\n\nconst int N = 1e5+1;\nvector<vector<int>> g(N);\n\nvector<int> sieve(N, 0);\nbool sieve_built = false;\n\nclass Solution {\n \n void BuildSieve() {\n if (sieve_built) return;\n \n sieve_built = true;\n \n for (int j = 2; j < N; j ++) {\n if (!sieve[j]) sieve[j] = j;\n \n for (int k = j+j; k < N; k += j) \n if (!sieve[k]) sieve[k] = j;\n }\n }\n \n bool IsPrime (int x) {\n return (sieve[x] == x);\n }\n \npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n BuildSieve();\n for (int j = 0; j <= n; j ++) g[j].clear();\n \n DSU dsu(n);\n \n for (auto i : edges) {\n int u = i[0], v = i[1];\n g[u].push_back(v);\n g[v].push_back(u);\n \n bool u_p = IsPrime(u);\n bool v_p = IsPrime(v);\n \n if (u_p || v_p) continue;\n dsu.Merge(u, v);\n }\n \n long long result = 0;\n for (int j = 1; j <= n; j ++) {\n if (!IsPrime(j)) continue;\n \n vector<int> nodes;\n long long sum = 1;\n \n for (auto e: g[j]) {\n if (IsPrime(e)) continue;\n \n nodes.push_back(dsu.cnt[dsu.Leader(e)]);\n sum += nodes.back();\n }\n \n for (auto i : nodes) {\n sum -= i;\n result += sum * i;\n }\n }\n return result;\n }\n};\n```
24
0
['C++']
2
count-valid-paths-in-a-tree
✅☑[C++/ C / Java/ Python/ JavaScript ] || Beats 100% || DP ||EXPLAINED🔥
c-c-java-python-javascript-beats-100-dp-ct4wh
PLEASE UPVOTE IF IT HELPED\n\n# Approach\n\n(Also explained in the code)\n\n1. genPrimes Function:\n\n- This function generates a list of prime numbers up to th
MarkSPhilip31
NORMAL
2023-09-24T04:42:43.137998+00:00
2023-10-18T09:48:30.692830+00:00
1,601
false
# *PLEASE UPVOTE IF IT HELPED*\n\n# Approach\n\n***(Also explained in the code)***\n\n1. `genPrimes` Function:\n\n- This function generates a list of prime numbers up to the given integer \'n\' using the Sieve of Eratosthenes algorithm.\n- It initializes a boolean vector `prime` of size `(n + 1)` to `true` for all numbers greater than or equal to 2. This marks them as potential prime numbers.\n- It then iterates through the numbers starting from 2 up to \'n\'. For each number \'i\', if it\'s marked as prime (`prime[i] == true`), it marks all its multiples in the vector as non-prime by setting `prime[j] = false`, where `j` is a multiple of \'i\'.\n- Finally, it returns the `prime` vector, where `prime[i]` indicates whether \'i\' is a prime number or not.\n\n2. `countPaths` Function:\n\n- This function calculates the count of paths in a tree-like structure based on the concept of prime and non-prime nodes.\n- It first calls the `genPrimes` function to generate a list of prime numbers up to \'n\' and stores it in the `isPrime` vector.\n- It creates an adjacency list `E` to represent the graph where each node has a list of neighboring nodes.\n- It then populates the adjacency list `E` based on the input \'edges\' that represent the connections between nodes.\n- The function uses a recursive depth-first search (DFS) approach to traverse the tree.\n- Inside the DFS function, for each node \'x\', it checks whether the node number (\'x + 1\') is prime using the `isPrime` vector.\n- It maintains an array `cur` to count the number of prime and non-prime nodes encountered during the traversal.\n- For each neighboring node \'y\', it recursively calls the DFS function and collects the counts from that subtree.\n- It updates the answer `ans` by counting the paths based on whether \'x\' and \'y\' are prime or non-prime nodes.\n- Finally, it returns the count array `cur` for the current node.\n3. The `countPaths` function is called with the root node as \'0\' and parent \'-1\' to start the DFS traversal from the root.\n\n# Complexity\n- **Time complexity:**\n$$O(n)$$\n\n- **Space complexity:**\n$$O(n)$$\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Helper function to generate prime numbers up to \'n\'.\n vector<bool> genPrimes(int n) {\n vector<bool> prime(n + 1);\n if (n > 1) fill(prime.begin() + 2, prime.end(), true); // Initializing all numbers >= 2 as prime.\n for (int i = 2; i <= n; ++i)\n if (prime[i])\n for (int j = i + i; j <= n; j += i)\n prime[j] = false; // Marking multiples of prime numbers as not prime.\n return prime;\n }\n \n // Main function to count paths based on prime numbers.\n long long countPaths(int n, vector<vector<int>>& edges) {\n auto isPrime = genPrimes(n); // Generate a list of prime numbers up to \'n\'.\n vector<vector<int>> E(n); // Creating an adjacency list for the graph.\n \n // Populate the adjacency list based on given edges.\n for (int i = 0; i < n - 1; ++i) {\n int u = edges[i][0], v = edges[i][1];\n --u;\n --v;\n E[u].push_back(v);\n E[v].push_back(u);\n }\n \n long long ans = 0; // Initialize the answer to zero.\n \n // Depth-first search (DFS) function to traverse the tree and count paths.\n function<array<int, 2>(int, int)> dfs = [&](int x, int p) {\n int prime = isPrime[x + 1]; // Check if the node number (1-based) is prime.\n array<int, 2> cur = {}; // Initialize an array to store counts based on prime status.\n cur[prime]++; // Update the count for prime or non-prime node.\n \n for (int y : E[x]) {\n if (y == p) continue; // Skip the parent node.\n auto v = dfs(y, x); // Recursively traverse the tree.\n \n // Update the answer by counting paths based on prime and non-prime nodes.\n ans += (long long)v[0] * cur[1];\n ans += (long long)v[1] * cur[0];\n \n cur[prime] += v[0]; // Update counts for the current node.\n \n if (!prime) cur[1 + prime] += v[1]; // If non-prime, update the count for non-prime nodes.\n }\n return cur; // Return the count array for the current node.\n };\n \n dfs(0, -1); // Start DFS from the root node (node 0) with parent -1.\n \n return ans; // Return the final count of paths.\n }\n}; \n```\n```C []\n#include <stdbool.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n// Function to generate prime numbers up to \'n\' and store them in an array.\nbool* genPrimes(int n) {\n bool* prime = (bool*)malloc((n + 1) * sizeof(bool));\n for (int i = 0; i <= n; ++i) {\n prime[i] = (i > 1); // Initializing all numbers >= 2 as prime.\n }\n \n for (int i = 2; i <= n; ++i) {\n if (prime[i]) {\n for (int j = i + i; j <= n; j += i) {\n prime[j] = false; // Marking multiples of prime numbers as not prime.\n }\n }\n }\n return prime;\n}\n\n// Depth-first search (DFS) function to traverse the tree and count paths based on prime numbers.\nlong long countPaths(int n, int** edges, int edgesSize, int* edgesColSize) {\n bool* isPrime = genPrimes(n); // Generate a list of prime numbers up to \'n\'.\n int** E = (int**)malloc(n * sizeof(int*)); // Creating an adjacency list for the graph.\n \n // Populate the adjacency list based on given edges.\n for (int i = 0; i < n; ++i) {\n E[i] = (int*)malloc(sizeof(int));\n }\n \n for (int i = 0; i < edgesSize; ++i) {\n int u = edges[i][0], v = edges[i][1];\n --u;\n --v;\n E[u] = (int*)realloc(E[u], (edgesColSize[i] + 1) * sizeof(int));\n E[u][edgesColSize[i]] = v;\n ++edgesColSize[i];\n E[v] = (int*)realloc(E[v], (edgesColSize[i] + 1) * sizeof(int));\n E[v][edgesColSize[i]] = u;\n ++edgesColSize[i];\n }\n \n long long ans = 0; // Initialize the answer to zero.\n \n // Depth-first search (DFS) function to traverse the tree and count paths.\n long long dfs(int x, int p) {\n int prime = isPrime[x + 1]; // Check if the node number (1-based) is prime.\n int cur[2] = {0}; // Initialize an array to store counts based on prime status.\n cur[prime]++; // Update the count for prime or non-prime node.\n \n for (int j = 0; j < edgesColSize[x]; ++j) {\n int y = E[x][j];\n if (y == p) continue; // Skip the parent node.\n int* v = (int*)malloc(2 * sizeof(int));\n v[0] = v[1] = 0;\n v = dfs(y, x); // Recursively traverse the tree.\n \n // Update the answer by counting paths based on prime and non-prime nodes.\n ans += (long long)v[0] * cur[1];\n ans += (long long)v[1] * cur[0];\n \n cur[prime] += v[0]; // Update counts for the current node.\n \n if (!prime) cur[1 + prime] += v[1]; // If non-prime, update the count for non-prime nodes.\n }\n \n return cur; // Return the count array for the current node.\n }\n \n // Start DFS from the root node (node 1) with parent -1.\n dfs(0, -1);\n \n // Free dynamically allocated memory.\n free(isPrime);\n \n for (int i = 0; i < n; ++i) {\n free(E[i]);\n }\n free(E);\n \n return ans; // Return the final count of paths.\n}\n\n```\n```Java []\nimport java.util.*;\n\nclass Solution {\n // Helper function to generate prime numbers up to \'n\'.\n private boolean[] genPrimes(int n) {\n boolean[] prime = new boolean[n + 1];\n if (n > 1) {\n Arrays.fill(prime, 2, prime.length, true); // Initializing all numbers >= 2 as prime.\n }\n for (int i = 2; i <= n; ++i) {\n if (prime[i]) {\n for (int j = i + i; j <= n; j += i) {\n prime[j] = false; // Marking multiples of prime numbers as not prime.\n }\n }\n }\n return prime;\n }\n\n // Main function to count paths based on prime numbers.\n public long countPaths(int n, int[][] edges) {\n boolean[] isPrime = genPrimes(n); // Generate a list of prime numbers up to \'n\'.\n List<List<Integer>> E = new ArrayList<>(n); // Creating an adjacency list for the graph.\n\n // Initialize the adjacency list.\n for (int i = 0; i < n; ++i) {\n E.add(new ArrayList<>());\n }\n\n // Populate the adjacency list based on given edges.\n for (int i = 0; i < n - 1; ++i) {\n int u = edges[i][0], v = edges[i][1];\n --u;\n --v;\n E.get(u).add(v);\n E.get(v).add(u);\n }\n\n long ans = 0; // Initialize the answer to zero.\n\n // Depth-first search (DFS) function to traverse the tree and count paths.\n Function<int[], int[]> dfs = (int[] arr) -> {\n int x = arr[0];\n int p = arr[1];\n int prime = isPrime[x + 1]; // Check if the node number (1-based) is prime.\n int[] cur = new int[2]; // Initialize an array to store counts based on prime status.\n cur[prime]++; // Update the count for prime or non-prime node.\n\n for (int y : E.get(x)) {\n if (y == p) continue; // Skip the parent node.\n int[] v = dfs.apply(new int[]{y, x}); // Recursively traverse the tree.\n\n // Update the answer by counting paths based on prime and non-prime nodes.\n ans += (long) v[0] * cur[1];\n ans += (long) v[1] * cur[0];\n\n cur[prime] += v[0]; // Update counts for the current node.\n\n if (prime == 0) cur[1 + prime] += v[1]; // If non-prime, update the count for non-prime nodes.\n }\n return cur; // Return the count array for the current node.\n };\n\n dfs.apply(new int[]{0, -1}); // Start DFS from the root node (node 0) with parent -1.\n\n return ans; // Return the final count of paths.\n }\n}\n\n```\n```Python3 []\nfrom collections import defaultdict\n\nclass Solution:\n def genPrimes(self, n):\n prime = [False] * (n + 1)\n if n > 1:\n prime[2:] = [True] * (n - 1) # Initializing all numbers >= 2 as prime.\n for i in range(2, n + 1):\n if prime[i]:\n for j in range(i + i, n + 1, i):\n prime[j] = False # Marking multiples of prime numbers as not prime.\n return prime\n\n def countPaths(self, n, edges):\n isPrime = self.genPrimes(n) # Generate a list of prime numbers up to \'n\'.\n E = defaultdict(list) # Creating an adjacency list for the graph.\n\n # Populate the adjacency list based on given edges.\n for u, v in edges:\n u -= 1\n v -= 1\n E[u].append(v)\n E[v].append(u)\n\n ans = 0 # Initialize the answer to zero.\n\n # Depth-first search (DFS) function to traverse the tree and count paths.\n def dfs(x, p):\n prime = isPrime[x + 1] # Check if the node number (1-based) is prime.\n cur = [0, 0] # Initialize an array to store counts based on prime status.\n cur[prime] += 1 # Update the count for prime or non-prime node.\n\n for y in E[x]:\n if y == p:\n continue # Skip the parent node.\n v = dfs(y, x) # Recursively traverse the tree.\n\n # Update the answer by counting paths based on prime and non-prime nodes.\n non_prime = 1 if prime == 0 else 0\n ans += v[0] * cur[non_prime]\n ans += v[1] * cur[prime]\n\n cur[prime] += v[0] # Update counts for the current node.\n cur[non_prime] += v[1] # If non-prime, update the count for non-prime nodes.\n\n return cur # Return the count array for the current node.\n\n dfs(0, -1) # Start DFS from the root node (node 0) with parent -1.\n\n return ans # Return the final count of paths.\n\n```\n```JavaScript []\nclass Solution {\n genPrimes(n) {\n const prime = new Array(n + 1).fill(false);\n if (n > 1) prime.fill(true, 2); // Initializing all numbers >= 2 as prime.\n for (let i = 2; i <= n; ++i) {\n if (prime[i]) {\n for (let j = i + i; j <= n; j += i) {\n prime[j] = false; // Marking multiples of prime numbers as not prime.\n }\n }\n }\n return prime;\n }\n\n countPaths(n, edges) {\n const isPrime = this.genPrimes(n); // Generate a list of prime numbers up to \'n\'.\n const E = new Array(n).fill().map(() => []); // Creating an adjacency list for the graph.\n\n // Populate the adjacency list based on given edges.\n for (const [u, v] of edges) {\n const uIdx = u - 1;\n const vIdx = v - 1;\n E[uIdx].push(vIdx);\n E[vIdx].push(uIdx);\n }\n\n let ans = 0; // Initialize the answer to zero.\n\n // Depth-first search (DFS) function to traverse the tree and count paths.\n const dfs = (x, p) => {\n const prime = isPrime[x + 1]; // Check if the node number (1-based) is prime.\n const cur = [0, 0]; // Initialize an array to store counts based on prime status.\n cur[prime] += 1; // Update the count for prime or non-prime node.\n\n for (const y of E[x]) {\n if (y === p) continue; // Skip the parent node.\n const v = dfs(y, x); // Recursively traverse the tree.\n\n // Update the answer by counting paths based on prime and non-prime nodes.\n const nonPrime = prime === 0 ? 1 : 0;\n ans += v[0] * cur[nonPrime];\n ans += v[1] * cur[prime];\n\n cur[prime] += v[0]; // Update counts for the current node.\n cur[nonPrime] += v[1]; // If non-prime, update the count for non-prime nodes.\n }\n return cur; // Return the count array for the current node.\n };\n\n dfs(0, -1); // Start DFS from the root node (node 0) with parent -1.\n\n return ans; // Return the final count of paths.\n }\n}\n\n```\n\n# *PLEASE UPVOTE IF IT HELPED*\n---\n\n\n---\n\n
18
0
['Array', 'Math', 'Dynamic Programming', 'Tree', 'Depth-First Search', 'C', 'C++', 'Java', 'Python3', 'JavaScript']
4
count-valid-paths-in-a-tree
C++ DSU Solution
c-dsu-solution-by-anujjadhav-2yss
Intuition\nWe are grouping the non-primes together separated by prime number\nAnd then for each primt numbers we try to find all the neighbouring groups of non-
AnujJadhav
NORMAL
2023-09-24T07:11:26.802976+00:00
2023-09-24T07:11:26.803002+00:00
1,254
false
# Intuition\nWe are grouping the non-primes together separated by prime number\nAnd then for each primt numbers we try to find all the neighbouring groups of non-prime\nthen total paths going through that prime no. can be easily calculated using simple maths\n\n# Code\n```\n#define ll long long\n\nclass Sieve {\npublic:\n vector<int> sieve; // isPrime or not\n int n;\n \n Sieve() {\n n = 0;\n }\n\n void init(int n) {\n if(this->n > 0) {\n return;\n }\n this->n = n;\n sieve = vector<int>(n + 1, true); // is prime or not\n sieve[0] = sieve[1] = false;\n for (int i = 2; i <= n; i++) {\n if (sieve[i]) {\n for (int j = i + i; j <= n; j += i) {\n sieve[j] = false;\n }\n }\n }\n }\n};\n\nclass DSU {\npublic:\n vector<int> parent;\n vector<int> rank;\n vector<int> size;\n\n DSU(int n) {\n rank = vector<int>(n);\n parent = vector<int>(n);\n size = vector<int>(n);\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n rank[i] = 0;\n size[i] = 1;\n }\n }\n\n int findPar(int node) {\n if (parent[node] == node) return node;\n return parent[node] = findPar(parent[node]);\n }\n\n void makeUnion(int u, int v) {\n u = findPar(u);\n v = findPar(v);\n\n if (rank[u] < rank[v]) {\n parent[u] = v;\n size[v] += size[u];\n } else if (rank[u] > rank[v]) {\n parent[v] = u;\n size[u] += size[v];\n } else {\n rank[u]++;\n parent[v] = u;\n size[u] += size[v];\n }\n }\n\n bool sameSet(int u, int v) {\n u = findPar(u);\n v = findPar(v);\n\n if (u == v) return true;\n return false;\n }\n};\n\n// Global\nSieve s;\n\nclass Solution {\npublic:\n \n vector<vector<int>> adj;\n \n bool isPrime(int num) {\n return s.sieve[num];\n }\n\n long long countPaths(int n, vector<vector<int>>& edges) {\n s.init(1e5 + 10);\n DSU dsu(n);\n adj = vector<vector<int>>(n);\n for(auto edge: edges) {\n int u = edge[0], v = edge[1];\n u--, v--;\n adj[u].push_back(v);\n adj[v].push_back(u);\n if(isPrime(u+1) || isPrime(v+1)) continue;\n dsu.makeUnion(u, v);\n }\n \n ll res = 0;\n \n for(int i = 0; i < n; i++) {\n if(isPrime(i+1) == false) continue;\n int node = i;\n ll currRes = 0;\n vector<ll> val;\n for(auto nbr: adj[node]) {\n if(isPrime(nbr+1)) continue;\n int sz = dsu.size[dsu.findPar(nbr)];\n res += sz;\n if(sz) val.push_back(sz);\n }\n if(val.size() == 0) continue;\n \n ll left = val[0];\n for(int j = 1; j < val.size(); j++) {\n res += val[j] * left;\n left += val[j];\n }\n }\n \n return res;\n }\n};\n```
17
0
['C++']
5
count-valid-paths-in-a-tree
[Python] DFS
python-dfs-by-awice-cjgr
If a node is prime, consider it to have weight 1. We want the number of paths with weight exactly 1.\n\nRoot the tree at 1 and consider the subtree at node. N
awice
NORMAL
2023-09-24T04:31:54.950219+00:00
2023-09-24T04:31:54.950238+00:00
541
false
If a node is prime, consider it to have weight 1. We want the number of paths with weight exactly 1.\n\nRoot the tree at `1` and consider the subtree at `node`. Now `c0, c1 = dfs(node, parent)` will be the number of paths starting at `node` in this subtree with sum `0` or `1` respectively. For a node $u$, lets call these values $u_0$ and $u_1$.\n\nNow consider when the path `u, v` in the tree has `LCA(u, v) = node`. There are two cases:\n\n$\\text{lca} \\notin \\{u, v\\}$: there are two arms of the path going from the LCA to u and v. The contribution is either $u_0 * v_0$ if the LCA has weight 1, or $u_0 + v_1 + u_1 * v_0$ otherwise.\n\n$\\text{lca} \\in \\{u, v\\}$: there is only one arm in the path, and the contribution is $u_0$ (LCA weight 1) or $u_1$ (LCA weight 0).\n\n# Code\n```\nMX = 100001\nlpf = [0] * MX\nfor i in range(2, MX):\n if lpf[i] == 0:\n for j in range(i, MX, i):\n lpf[j] = i\n\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n adj = [[] for _ in range(n+1)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n \n self.ans = 0\n def dfs(node, par):\n prime = lpf[node] == node\n\n s0 = s1 = 0\n for nei in adj[node]:\n if nei != par:\n c0, c1 = dfs(nei, node)\n \n # answer for LCA(u, v) = node, node not in [u, v]\n if prime:\n self.ans += s0 * c0\n else:\n self.ans += s0 * c1 + s1 * c0\n \n s0 += c0\n s1 += c1\n \n # answer for LCA(u, v) = node, node in [u, v]\n if not prime:\n self.ans += s1\n return s0 + 1, s1\n else:\n self.ans += s0\n return 0, s0 + 1\n\n dfs(1, 0)\n return self.ans\n```
11
0
['Python3']
1
count-valid-paths-in-a-tree
🔥Just 2 DFS || C++ ||
just-2-dfs-c-by-jainwinn-l6rt
\n# Code\n\nclass Solution {\npublic:\n //here for each node we store sum of nodes below a given node such that there is no prime along the path in sum array
JainWinn
NORMAL
2023-09-24T04:20:48.066881+00:00
2023-09-24T07:04:38.739184+00:00
937
false
\n# Code\n```\nclass Solution {\npublic:\n //here for each node we store sum of nodes below a given node such that there is no prime along the path in sum array.\n //also we store number of nodes without prime for each path from the node in dist array(only for primes) .\n long long dfs(int curr,vector<vector<int>> &adj,vector<int> &vis,vector<vector<long long>> &dist , vector<bool> &isprime,vector<long long> &sum){\n long long val=0;\n vis[curr]=1;\n for(auto nbr : adj[curr]){\n if(!vis[nbr]){\n long long nodes_without_prime=dfs(nbr,adj,vis,dist,isprime,sum);\n val+=nodes_without_prime;\n if(isprime[curr] && nodes_without_prime!=0){\n dist[curr].push_back(nodes_without_prime);\n }\n }\n }\n sum[curr]=val;\n return isprime[curr] ? 0 : val+1;\n }\n \n //Here we find the max possible number of nodes in path without prime above the node . \n long long dfs2(int curr,int nodes_above_without_prime,vector<vector<int>> &adj,vector<int> &vis,vector<vector<long long>> &dist , vector<bool> &isprime,vector<long long> &sum){\n long long val=0;\n vis[curr]=1;\n if(isprime[curr]){\n dist[curr].push_back(nodes_above_without_prime);\n nodes_above_without_prime=0;\n }\n if(!isprime[curr]){\n if(nodes_above_without_prime==0){\n nodes_above_without_prime+=1+sum[curr];\n }\n }\n \n for(auto nbr : adj[curr]){\n if(!vis[nbr]){\n long long nodes_without_prime=dfs2(nbr,nodes_above_without_prime,adj,vis,dist,isprime,sum);\n val+=nodes_without_prime;\n }\n }\n\n return isprime[curr] ? 0 : val+1;\n }\n \n \n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<vector<int>> adj(n+1);\n for(int i=0 ; i<edges.size() ; i++){\n adj[edges[i][0]].push_back(edges[i][1]);\n adj[edges[i][1]].push_back(edges[i][0]);\n }\n vector<bool> isprime(n+1,1);\n isprime[1]=0;\n for(long long i=2 ; i<=n ; i++){\n if(isprime[i]==0){\n continue;\n }\n isprime[i]=1;\n for(long long j=i*i ; j<=n ; j+=i){\n isprime[j]=0;\n }\n }\n long long ans=0;\n vector<int> vis(n+1,0);\n vector<vector<long long>> dist(n+1);\n vector<long long> sum(n+1,0);\n dfs(1,adj,vis,dist,isprime,sum);\n for(int i=0 ; i<=n ; i++){\n vis[i]=0;\n }\n dfs2(1,0,adj,vis,dist,isprime,sum);\n for(int curr=2 ; curr<=n ; curr++){\n if(isprime[curr]){\n long long total=0;\n for(auto ele : dist[curr]){\n total+=ele;\n }\n for(int i=0 ; i<dist[curr].size() ; i++){\n if(dist[curr][i]==0){\n continue;\n }\n ans+=(total-dist[curr][i]+(long long)1)*dist[curr][i];\n total-=dist[curr][i];\n }\n \n }\n }\n return ans;\n }\n};\n```\n\nPS : Just got accepted after the contest as I forgot to mark all nodes unvisited before dfs2\uD83D\uDE2D
4
0
['Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
Java | Dfs | One pass | self explanatory
java-dfs-one-pass-self-explanatory-by-je-c1qg
Approach\nRun dfs starting from first node.\nFor every iteration return 2 values\n - numbers of pathes discovered so far which has exactly one prime\n - number
jeckafedorov
NORMAL
2023-09-24T04:18:15.691614+00:00
2023-09-24T04:18:15.691633+00:00
498
false
# Approach\nRun dfs starting from first node.\nFor every iteration return 2 values\n - numbers of pathes discovered so far which has exactly one prime\n - number of pathes discovered so far which has no prime\n\nDepends on current node (if it is prime or node) add to result\npathes which ends in current node and pathes which intersect in current node.\n\n\n\n# Code\n```\nclass Solution {\n List<Integer>[] G;\n long ans = 0;\n public long countPaths(int n, int[][] edges) {\n G = new ArrayList[n+1];\n for (int i=0; i <= n; i++) {\n G[i] = new ArrayList<>();\n }\n for (int[] e : edges) {\n G[e[0]].add(e[1]);\n G[e[1]].add(e[0]);\n }\n dfs(1, -1);\n return ans;\n }\n \n\n public long[] dfs(int u, int prev) { \n \n boolean isp = isPrime(u);\n \n long primeChildren = 0;\n long nonPrimeChildren = 0;\n \n for (int v : G[u]) {\n if (v == prev) {\n continue;\n }\n long[] next = dfs(v, u);\n if ( ! isp) {\n ans += primeChildren * next[1];\n ans += nonPrimeChildren * next[0];\n } else {\n ans += nonPrimeChildren * next[1];\n } \n primeChildren += next[0];\n nonPrimeChildren += next[1];\n }\n \n long[] res = new long[2];\n if (isp) {\n ans += nonPrimeChildren;\n res[0] = nonPrimeChildren+1;\n } else {\n ans += primeChildren;\n res[0] = primeChildren;\n res[1] = nonPrimeChildren+1;\n }\n return res;\n }\n \n \n public boolean isPrime(int n) {\n if (n <= 1)\n return false;\n for (int i = 2; i <= Math.sqrt(n); i++)\n if (n % i == 0)\n return false;\n return true;\n }\n}\n```
4
0
['Java']
4
count-valid-paths-in-a-tree
[C++] DFS solution O(N)
c-dfs-solution-on-by-pr0d1g4ls0n-4is0
Intuition\n Describe your first thoughts on how to solve this problem. \nDFS through path, intuition similar to binary tree maximum path.\nhttps://leetcode.com/
pr0d1g4ls0n
NORMAL
2023-09-24T04:15:42.950337+00:00
2023-09-24T12:37:13.461649+00:00
514
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDFS through path, intuition similar to binary tree maximum path.\nhttps://leetcode.com/problems/binary-tree-maximum-path-sum/\n\nAt each node:\n1. Calculate subtree path ending at node.\n2. Calculate two subtree paths that go through current node.\n\nKeep an array for each recursive case which tracks paths that contain 0 and 1 prime number.\n\n# FAQ\n<!-- Describe your approach to solving the problem. -->\n\n1. How do you track paths that use current node as a conduit. i.e. they go through current node but end in left subtree and right subtree.\n\n### Explanation\nIf current node is a prime number, to use it as a conduit, you must have two paths with no primes numbers from separate subtrees.\n\nIf current node is not a prime number, to use it as a conduit, you must have two different paths, one path with one prime number and the other with zero prime numbers. Both paths must also be from different subtrees.\n\n2. Can you please explain why two subtree paths that go through current node is calculated as following?\n\n```\n// curr is conduit for path\nans += (count[1] * next[0]); \n```\n\n### Explanation:\nIf node A is prime, then you can get single prime paths with A as conduit for two separate subtree paths with zero prime numbers.\n\nAs you loop through each subtree, you track the number of zero prime number subtree paths encountered in `count[1]` as seen in:\n```\ncount[1] += next[0];\n```\nEach zero prime subtree path that you loop through, you can do a product on previously encountered zero prime subtree path. Which is stored in `count[1]`.\n\nTherefore, you add to `ans` the product of `count[1]` and `next[0]`.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n# Code\n```\nclass Solution {\npublic:\n vector<int> primes;\n long long ans = 0;\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<vector<int>> adjlist(n+1);\n for (auto edge : edges) {\n adjlist[edge[0]].push_back(edge[1]);\n adjlist[edge[1]].push_back(edge[0]);\n }\n primes = vector<int>(n+5, 1);\n primes[1] = 0;\n for (int i = 2; i < sqrt(primes.size()); ++i) {\n if (primes[i] == 0) continue;\n for (int j = i * i; j < primes.size(); j += i) {\n primes[j] = 0;\n }\n }\n \n dfs(1, -1, adjlist);\n return ans;\n }\n \n vector<int> dfs(int curr, int parent, vector<vector<int>>& adjlist) {\n vector<int> count{0,0};\n bool isprime = primes[curr];\n\n for (auto child : adjlist[curr]) {\n if (child == parent) continue;\n vector<int> next = dfs(child, curr, adjlist);\n if (isprime) {\n // count paths that ends at curr\n ans += next[0];\n // count paths that use curr as a conduit\n ans += (count[1] * next[0]);\n \n count[1] += next[0];\n } else {\n // count paths that ends at curr\n ans += next[1];\n // count paths that use curr as conduit\n ans += (count[0] * next[1]);\n ans += (count[1] * next[0]);\n \n count[0] += next[0];\n count[1] += next[1];\n }\n }\n \n count[isprime]++;\n return count;\n }\n};\n```
4
0
['C++']
3
count-valid-paths-in-a-tree
Java | Dfs | One pass with comments
java-dfs-one-pass-with-comments-by-jecka-frs8
Approach\nRun dfs starting from first node.\nFor every iteration return 2 values\n - numbers of pathes discovered so far which has exactly one prime\n - number
jeckafedorov
NORMAL
2023-09-25T22:38:22.810223+00:00
2023-09-25T22:38:22.810257+00:00
91
false
# Approach\nRun dfs starting from first node.\nFor every iteration return 2 values\n - numbers of pathes discovered so far which has exactly one prime\n - number of pathes discovered so far which has no prime\n\nDepends on current node (if it is prime or node) add to result\npathes which ends in current node and pathes which intersect in current node.\n\n\n\n# Code\n```\nclass Solution {\n List<Integer>[] G;\n long ans = 0;\n public long countPaths(int n, int[][] edges) {\n G = new ArrayList[n+1];\n for (int i=0; i <= n; i++) {\n G[i] = new ArrayList<>();\n }\n for (int[] e : edges) {\n G[e[0]].add(e[1]);\n G[e[1]].add(e[0]);\n }\n dfs(1, -1);\n return ans;\n }\n \n\n public int[] dfs(int u, int prev) { \n \n // check if current node is prime\n boolean isp = isPrime(u);\n \n int primeChildren = 0;\n int nonPrimeChildren = 0;\n \n for (int v : G[u]) {\n if (v == prev) {\n continue;\n }\n int[] next = dfs(v, u);\n if (isp) {\n // if current is prime\n // combine paths with 0 primes from next child\n // with 0 primes paths from other children seen so far\n // which makes our current prime node the only prime node\n // in the middle of all the paths\n // Also combine again (+1) current node with all 0 primes\n // from next child which makes our current prime node\n // the only prime node at the end of the path\n ans += (nonPrimeChildren+1) * next[0];\n } else {\n // if current is not prime\n // combine paths with 0 primes from next child with\n // prime paths from other children seen so far\n // our current non prime node will be in the middle\n ans += primeChildren * next[0];\n // combine path with 1 prime paths from next child\n // with 0 primes paths from other children seen so far\n // our current non prime node will be in the middle.\n // Also combine again (+1) 1 prime paths from next child\n // with current node. The current node will be at the end.\n ans += (nonPrimeChildren+1) * next[1];\n } \n primeChildren += next[1];\n nonPrimeChildren += next[0];\n }\n\n int[] res = new int[2];\n\n // 0 index returns number of 0 prime paths. If current node is prime\n // it is impossible to make any 0 prime paths, so return 0/\n // if current node is not prime, all children 0 prime paths will still\n // have 0 primes, also current node start new 0 prime paths.\n res[0] = isp ? 0 : nonPrimeChildren+1;\n\n // 1 index returns number of 1 prime paths to the parent.\n // if current node is prime, we can only combine our current\n // with other 0 prime chidlren paths.\n // If current node is not prime, 1 prime children paths will still\n // make the same number of 1 prime paths in combination with current node\n res[1] = isp ? nonPrimeChildren+1 : primeChildren;\n return res;\n }\n \n \n public boolean isPrime(int n) {\n if (n <= 1)\n return false;\n for (int i = 2; i <= Math.sqrt(n); i++)\n if (n % i == 0)\n return false;\n return true;\n }\n}\n```
3
0
['Java']
0
count-valid-paths-in-a-tree
O(N+ N log N) Solution using DFS| C++|
on-n-log-n-solution-using-dfs-c-by-coder-9vyn
Approach: \nFor every node I will keep track of two things:\n1) Number of nodes in its subtree that have non-prime labels and the path to them also contains onl
coder_gogeta
NORMAL
2023-09-25T11:27:59.297964+00:00
2023-09-26T13:26:49.929851+00:00
513
false
### Approach: \nFor every node I will keep track of two things:\n1) Number of nodes in its subtree that have non-prime labels and the path to them also contains only non-prime labels, I will call such nodes in the subtree as non-prime nodes. \n2) Number of nodes in its subtree that have prime labels and the path to them contains exactly one prime label, I will call such nodes in the subtree as prime nodes. \n\nI will call the function dfs for recursively for every node, at each node it calculates the number of paths with exactly one prime node between 2 nodes where both nodes are in different children\'s subtree (i.e. the number of valid paths through this node.).\nThe condition to not include nodes in same child\'s subtree is there to prevent multiple counting of same valid path in the parent, grandparent nodes.\n\n\nAt each node:\n* Total number of prime nodes: sum of prime nodes in child nodes\n* Total number of non prime nodes: sum of non prime nodes in child nodes +1 \n\nAt each function call, there are 2 cases for a node :\n1) If the node has a non-prime label then the paths between :\n* A non-prime node and a prime node (both in different children\'s subtree) will have exactly one prime label. So these paths will be valid.\n* A non-prime node and another non-prime node (both in different children\'s subtree) will have no prime label.\n* A prime node and a prime nodes (both in different children\'s subtree) will have exactly two prime labels.\n\n2) If the node has a prime label then the paths between :\n* A non-prime node and a prime node (both in different children\'s subtree) will have exactly two prime labels. \n* A non-prime node and another non-prime node (both in different children\'s subtree) will have exactly one prime label .So these paths will be valid.\n* A prime node and a prime nodes (both in different children\'s subtree) will have exactly three prime labels.\n* After the number of valids paths are calculated through the node , I will update the number of prime nodes to sum of non prime nodes in children and number of non prime nodes to zero. \n**Reason:** This is done as all the paths to prime nodes from parent or grandparent of current node will have two ( more than 1) prime labels so keeping track of these nodes will beuseless all the remaining paths through them will not be valid and all the paths to the non prime nodes from parent or grandparent of current node will have 1 prime labels.\n\n**Note:** I will using sieve of eratosthenes to pre calculate which node labels are prime and non prime.\n**Time Complexity:** O(N+N logN), we need O(N) time for dfs function and O(N logN) for sieve of eratosthenes.\n**Memory Analysis:** O(N) , one array to keep track of which node label is prime and non prime and other array in dfs fucntion to keep track of number of prime and non prime nodes in children nodes.\n\n``` \nclass Solution {\npublic:\n \n void dfs(vector<vector<int>> &edge,vector<int> &isprime,int node,int last,long long int &ans,int &prime,int &non_prime){\n \n int m=edge[node].size();\n vector<vector<int>> nums;\n for(int i=0;i<m;i++){\n \n if(edge[node][i]!=last){\n \n int temp1=0; int temp2=0;\n dfs(edge,isprime,edge[node][i],node,ans,temp1,temp2);\n nums.push_back({temp1,temp2});\n prime+=temp1;\n non_prime+=temp2;\n }\n \n }\n \n \n \n if(isprime[node+1]==1){\n \n non_prime++;\n int temp=non_prime;\n prime=non_prime;\n non_prime=0;\n \n for(int i=0;i<(nums.size());i++){\n \n temp-=nums[i][1];\n ans+=(1LL*temp*nums[i][1]);\n }\n \n }else{\n \n \n non_prime++;\n int temp=non_prime;\n for(int i=0;i<(nums.size());i++){\n \n temp-=nums[i][1];\n ans+=(1LL*temp*nums[i][0]);\n temp+=nums[i][1];\n }\n \n }\n \n }\n long long countPaths(int n, vector<vector<int>>& graph) {\n \n \n int m=graph.size();\n vector<vector<int>> edge(n);\n \n for(int i=0;i<m;i++){\n edge[graph[i][0]-1].push_back(graph[i][1]-1);\n edge[graph[i][1]-1].push_back(graph[i][0]-1);\n }\n \n \n \n long long int ans=0;\n int prime=0;\n int non_prime=0;\n \n \n \n vector<int> isprime(n+3,1);\n isprime[0]=0; isprime[1]=0;\n \n for(int i=2;i<=n;i++){\n if(isprime[i]==1){\n int j=2;\n while((i*j)<=n){\n isprime[i*j]=0;\n j++;\n }\n }\n }\n dfs(edge,isprime,0,-1,ans,prime,non_prime);\n return(ans);\n }\n};\n```
3
0
[]
1
count-valid-paths-in-a-tree
✅ C++ || DSU || Beats 100% || Intuition and Explanation 🔥🔥🔥
c-dsu-beats-100-intuition-and-explanatio-lgcd
Intuition\n Describe your first thoughts on how to solve this problem.\n \nThe main concept is to count non-prime children of a prime node and merging them usin
RuntimeErr0r
NORMAL
2023-09-25T11:07:58.949864+00:00
2023-09-25T11:07:58.949887+00:00
202
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem.\n -->\nThe main concept is to count non-prime children of a prime node and merging them using disjoint set algorithm.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Get all the prime numbers upto n and store them in a vector using sieve of eratosthenes.\n2. Implement class for DSU which merges nodes using their rank or count.\n3. Create an adj list for graph. If there exists an edge u-v such that both u and v are non-prime, unite them using dsu.\n4. Now count result. Iterate from 1 to n, if any prime number i is encountered, get all non-prime child of this number and put their merging count in a vector child. After that get total sum of this child vector. To count number of paths crossing this prime number i, we will use child array i.e., from child vector get an element, substract it from sum and increment the answer by sum*element.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> \n O(n)\n\n# Code\n```\nclass DSU{\npublic:\n vector<int> par;\n vector<int> cnt;\n\n DSU(int n){\n par.resize(n+1);\n cnt.resize(n+1,1);\n\n for(int i=0;i<=n;i++) par[i]=i;\n }\n\n int abs_par(int x){\n if(x==par[x]) return x;\n return par[x]=abs_par(par[x]);\n }\n\n void unite(int a, int b){\n int abs_a=abs_par(a);\n int abs_b=abs_par(b);\n\n if(abs_a==abs_b) return;\n\n if(cnt[abs_a]>cnt[abs_b]) swap(a,b);\n\n cnt[abs_b]+=cnt[abs_a];\n par[abs_a]=abs_b;\n\n }\n\n};\n\nclass Solution {\npublic:\n\n long long countPaths(int n, vector<vector<int>>& edges) {\n\n //getting all the prime numbers\n vector<bool> is_prime(n+1,true);\n is_prime[0] = is_prime[1] = false;\n for (int p = 2; p * p <= n; p++) {\n if (is_prime[p]) {\n for (int i = p * p; i <= n; i += p) {\n is_prime[i] = false;\n }\n }\n }\n \n //getting adjlist from edges and uniting nodes if none of them are prime\n DSU dsu(n);\n vector<int> adj[n+1];\n for(auto& e:edges){\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n\n if(is_prime[e[0]]||is_prime[e[1]]) continue;\n\n dsu.unite(e[0],e[1]);\n }\n\n long long ans=0;\n for(int i=1;i<=n;i++){\n if(!is_prime[i]) continue;\n\n vector<long long> child;\n for(auto& x:adj[i]){\n if(is_prime[x]) continue;\n int par_x=dsu.abs_par(x);\n child.push_back(dsu.cnt[par_x]);\n }\n long long sum=accumulate(child.begin(),child.end(),1);\n for(auto& c:child){\n sum-=c;\n ans+=sum*c;\n }\n }\n\n return ans;\n }\n};\n```
3
0
['Union Find', 'Graph', 'C++']
0
count-valid-paths-in-a-tree
Complete Contest Video Solution | Explanation With Drawings | In Depth
complete-contest-video-solution-explanat-0701
Intuition and approach discussed in detail in video solution\nhttps://youtu.be/A2ynfP81UW4\n# Code\n\n// https://cp-algorithms.com/data_structures/disjoint_set_
Fly_ing__Rhi_no
NORMAL
2023-09-24T10:32:51.145964+00:00
2023-09-24T10:32:51.145982+00:00
215
false
# Intuition and approach discussed in detail in video solution\nhttps://youtu.be/A2ynfP81UW4\n# Code\n```\n// https://cp-algorithms.com/data_structures/disjoint_set_union.html\n// https://cp-algorithms.com/algebra/sieve-of-eratosthenes.html\n// ---------------------------------------------------------------------------------------------------------------------------------------\n\n//implementation of disjoint set union\nstruct dsu {\n vector<int> parent;\n int n;\n dsu(int n) : n(n) { clear(); }\n void clear(){ parent.assign(n, -1); }\n int find(int u){ return (parent[u] < 0) ? u : parent[u] = find(parent[u]); }\n bool same(int u, int v){ return find(u) == find(v); }\n bool join(int u, int v){\n u = find(u);\n v = find(v);\n if (u != v){\n if (parent[u] > parent[v])\n swap(u, v);\n parent[u] += parent[v];\n parent[v] = u;\n }\n return u != v;\n }\n int size(int u){ return -parent[find(u)]; }\n};\n\nclass Solution {\npublic:\n void sieve(vector<int>& is_prime, int n){\n is_prime[1] = 0; is_prime[1] = 0;\n for(long long i = 2; i <= n; i++){\n if(!is_prime[i]) continue;\n for(long long j = i * i; j <= n; j += i) is_prime[j] = 0;\n }\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n //sieve of eratosthenese\n //used for checking whether a number is prime or not\n vector<int> is_prime(n + 1, 1);\n sieve(is_prime, n);\n\n //union find\n dsu union_find(n + 1);\n // making graph according to edges array \n vector<vector<int>> graph(n + 1);\n for(int indx = 0; indx < n - 1; indx++){\n int u = edges[indx][0], v = edges[indx][1];\n //you will be forming bi directional edges\n graph[u].push_back(v);\n graph[v].push_back(u);\n }\n\n\n //using union find\n //first forming path without primes numbers in it\n for(int node = 1; node <= n; node++){\n //if a current node is a prime number than you will skip it\n if(is_prime[node]) continue;\n //check for the neighbors of that current node which are not prime\n for(int neigh : graph[node]){\n if(is_prime[neigh]) continue;\n union_find.join(node, neigh);\n }\n }\n long long numberOfValidPaths = 0;\n //now adding primes to path without primes at different nodes available in the non prime paths\n for(int node = 1; node <= n; node++){\n //we will consider a node only if it\'s a prime node\n if(!is_prime[node]) continue;\n long long not_primes = 1ll;\n //considering those paths which are attached to a prime number\n for(int neigh : graph[node]){\n if(is_prime[neigh]) continue;//2 primes are not allowed in a path\n //attaching current path to existing paths\n numberOfValidPaths += not_primes * union_find.size(neigh);\n not_primes += union_find.size(neigh) * 1ll; //number of not primes will increase\n //these not primes will be used when all these non primes nodes can be attached to some other prime number, since a tree is a connected graph\n \n }\n }\n return numberOfValidPaths;\n }\n};\n\n```
3
0
['C++']
0
count-valid-paths-in-a-tree
Very intuitive approach using tree in-out dp (beats 100% in memory use)
very-intuitive-approach-using-tree-in-ou-7iay
Intuition\n Describe your first thoughts on how to solve this problem. \n Lets consider each vertex , if we can find the number of path starting from this verte
i_m_karank
NORMAL
2023-09-24T06:49:06.851994+00:00
2023-09-24T06:49:06.852024+00:00
149
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n Lets consider each vertex , if we can find the number of path starting from this vertex and have exactly one prime number , then we are done, we will add the contribution of each vertex to get our final answer \n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each vertex we will keep a indp[node][0/1] which will tell the number of path which starts from node and goes into it\'s subtree having 0/1 prime in it, and one outdp[node][0/1] which will tell the number of path starting from present node and goes into any ancestor and it\'s child and has 0/1 prime in it.\n\nHaving this as our dp states one can easily realize the transitions ,which i\'m leaving for the reader to find out, if you can\'t come with transitions refer to the code.\n\nPS: for checking prime precalculate the seive array before doing dfs\n# Complexity\n- Time complexity:\n O(n+nlog(n))\n \n- Space complexity:\n O(n)\n\n# Code\n```\nvector<vector<int>>indp,outdp,g;\nvector<int>spf;\nvoid indfs(int node,int par){\n for(auto v:g[node]){\n if(v!=par){\n indfs(v,node);\n if(spf[node]==node){\n if(spf[v]==v){\n\n }\n else{\n indp[node][1]+=(indp[v][0]+1);\n }\n }\n else{\n if(spf[v]==v){\n indp[node][1]+=(indp[v][1]+1);\n }\n else{\n indp[node][0]+=(indp[v][0]+1);\n indp[node][1]+=(indp[v][1]);\n }\n }\n }\n }\n\n}\nvoid outdfs(int node,int par){\n if(par){\n if(spf[node]==node){\n if(spf[par]==par){\n // do nothing as 0 path\n }\n else{\n outdp[node][1]=(outdp[par][0]+indp[par][0]+1);\n }\n }\n else{\n if(spf[par]==par){\n outdp[node][1]=(outdp[par][1]+indp[par][1]-indp[node][0]);\n }\n else{\n outdp[node][1]=(outdp[par][1]+indp[par][1]-indp[node][1]);\n outdp[node][0]=(outdp[par][0]+indp[par][0]-indp[node][0]);\n }\n }\n }\n for(auto v:g[node]){\n if(v!=par) outdfs(v,node);\n }\n}\nclass Solution {\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n g.assign(n+1,vector<int>());\n indp.assign(n+1,vector<int>(2,0));\n outdp.assign(n+1,vector<int>(2,0));\n spf.assign(n+2,0);\n for(auto arr:edges){\n g[arr[0]].push_back(arr[1]);\n g[arr[1]].push_back(arr[0]);\n }\n for(int i=2;i<=n;i++){\n if(!spf[i]){\n for(int j=i;j<=n;j+=i){\n if(!spf[j]) spf[j]=i;\n }\n }\n }\n \n indfs(1,0);\n outdfs(1,0);\n long long ans=0;\n for(int i=1;i<=n;i++){\n // cout<<outdp[i][1]<<" "<<outdp[i][0]<<endl;\n ans+=(1ll*indp[i][1]+outdp[i][1]);\n }\n return ans/2;\n }\n};\n```
3
0
['C++']
3
count-valid-paths-in-a-tree
Union Find Based Solution
union-find-based-solution-by-sushantk_04-d9h7
Intuition\n Describe your first thoughts on how to solve this problem. \nEach prime node in the tree will split the tree and groups will form within the tree.\n
sushantk_04
NORMAL
2023-09-24T05:12:04.612896+00:00
2023-09-24T06:07:36.585372+00:00
408
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEach prime node in the tree will split the tree and groups will form within the tree.\n\nNow suppose this node have 3 neighbours so the total no of paths for this prime node will be - \n\nNegh 1 belong to Group A total node in group is 5\nNegh 2 belong to Group B total node in group is 4\nNegh 3 belong to Group C total node in group is 3\n\nTP = 0\nCASE 1: Prime node can pair up any node to form a path so TP += 5+4+3\nCASE 2: Node from one group can pair up with nodes from other groups to form a path through prime node.\nTP += (No of Nodes in this group) * (No of nodes in other groups)\n\nComputing no of nodes in a group can have TC O(n)\nWe can optimize this by Grouping all node using Union Find and storing no of nodes for this group in parent node.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\n\nclass Solution {\npublic:\n vector<bool> primes;\n \n void createPrimes(){\n int n = 1e5;\n primes.resize(n+1, true);\n primes[0] = primes[1] = false;\n \n for(int i=2; i<=n; i++){\n if(primes[i]){\n for(int j=2*i; j<=n; j+=i) primes[j] = false;\n }\n }\n }\n \n unordered_map<int,vector<int>> g;\n long long ans = 0;\n vector<int> parent;\n vector<bool> visited;\n unordered_map<int,int> nodesInGroup;\n \n int findParent(int node){\n if(parent[node] == node) return node;\n return parent[node] = findParent(parent[node]);\n }\n \n void formGroups(int node){\n if(visited[node]) return;\n visited[node] = true;\n \n for(auto &negh: g[node]){\n if(primes[negh]) continue;\n int p1 = findParent(node);\n int p2 = findParent(negh);\n parent[p2] = p1;\n formGroups(negh);\n }\n }\n \n void calculateNoOfNodesInGroup(int n){\n \n for(int i=0; i<n; i++){\n int p1 = findParent(i);\n nodesInGroup[p1]++;\n }\n }\n \n \n long long countPaths(int n, vector<vector<int>>& edges) {\n createPrimes();\n parent.resize(n+1,0);\n visited.resize(n+1, false);\n \n for(int i=0; i<n; i++) parent[i] = i;\n \n for(auto &edge: edges){\n g[edge[0]].push_back(edge[1]);\n g[edge[1]].push_back(edge[0]);\n }\n \n for(int i=0; i<n; i++){\n if(!primes[i]) formGroups(i);\n }\n \n calculateNoOfNodesInGroup(n);\n \n long long ans = 0;\n \n for(int i=1; i<=n; i++){\n if(primes[i]) {\n long long totalNodeInPrevGroups = 1;\n for(auto &negh: g[i]){\n if(primes[negh]) continue;\n int p1 = findParent(negh);\n ans += totalNodeInPrevGroups * nodesInGroup[p1];\n totalNodeInPrevGroups += nodesInGroup[p1];\n }\n }\n }\n return ans;\n }\n};\n```
3
0
['C++']
1
count-valid-paths-in-a-tree
Divide and Conquer + Backtracking [EXPLAINED]
divide-and-conquer-backtracking-explaine-iso4
IntuitionThe key to solving this problem is recognizing that a valid path between two nodes in a tree must contain exactly one prime number. To do this, we need
r9n
NORMAL
2025-01-15T23:02:17.218204+00:00
2025-01-15T23:02:17.218204+00:00
12
false
# Intuition The key to solving this problem is recognizing that a valid path between two nodes in a tree must contain exactly one prime number. To do this, we need to traverse the tree, count the prime numbers along the way, and check if the path meets the condition of having exactly one prime number. # Approach Use DFS to explore the tree, where at each node we track the number of paths that contain one prime node. We start by marking all prime numbers using the Sieve of Eratosthenes, then traverse the tree, updating the result whenever we find a valid path that includes # Complexity - Time complexity: 𝑂 (𝑛 log ⁡log ⁡𝑛) because of the sieve to identify prime numbers and 𝑂(𝑛) for the DFS traversal, so overall it is dominated by the sieve, which is efficient for this problem. - Space complexity: O(n) since we store the adjacency list for the tree and the prime markings, both requiring space proportional to the number of nodes in the tree. # Code ```python3 [] class Solution: def __init__(self): self.res = 0 def countPaths(self, n: int, edges: List[List[int]]) -> int: adj = [[] for _ in range(n + 1)] is_prime = [0] * (n + 1) # Sieve of Eratosthenes to mark primes is_prime[1] = 1 for i in range(2, int(n ** 0.5) + 1): if is_prime[i] == 1: continue for j in range(i * i, n + 1, i): is_prime[j] = 1 # Create adjacency list for u, v in edges: adj[u].append(v) adj[v].append(u) # DFS helper function def dfs(node: int, parent: int) -> List[int]: prime0, prime1 = 0, 0 if is_prime[node] == 0: prime1 += 1 else: prime0 += 1 for neighbor in adj[node]: if neighbor != parent: v0, v1 = dfs(neighbor, node) self.res += prime0 * v1 + prime1 * v0 if is_prime[node] == 0: prime1 += v0 else: prime0 += v0 if is_prime[node] == 1: prime1 += v1 return prime0, prime1 # Start DFS from node 1 dfs(1, -1) return self.res ```
2
0
['Math', 'Divide and Conquer', 'Dynamic Programming', 'Backtracking', 'Depth-First Search', 'Breadth-First Search', 'Graph', 'Combinatorics', 'Python3']
0
count-valid-paths-in-a-tree
Python (Simple DFS)
python-simple-dfs-by-rnotappl-iicn
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
rnotappl
NORMAL
2023-10-11T21:17:51.184608+00:00
2023-10-11T21:17:51.184638+00:00
37
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countPaths(self, n, edges):\n # Build graph\n\n dict1 = defaultdict(list)\n\n for i,j in edges:\n dict1[i].append(j)\n dict1[j].append(i)\n\n # Use sieve of Eratosthenes\n\n is_primes = [False]*2 + [True]*(n-1)\n\n for p in range(2,n+1):\n if is_primes[p]:\n for j in range(2*p,n+1,p):\n is_primes[j] = False\n\n # DFS\n\n self.total = 0\n\n def dfs(start,end):\n ans = [1-is_primes[start],is_primes[start]]\n\n for neighbor in dict1[start]:\n if neighbor == end: continue\n non_prime_path, prime_path = dfs(neighbor,start)\n self.total += non_prime_path*ans[1] + prime_path*ans[0]\n\n if is_primes[start]:\n ans[1] += non_prime_path\n else:\n ans[0] += non_prime_path\n ans[1] += prime_path\n\n return ans\n\n dfs(1,0)\n\n return self.total\n\n\n\n\n\n\n\n\n \n\n\n \n \n \n```
2
0
['Python3']
0
count-valid-paths-in-a-tree
Easy and Beginner friendly || Sieve || DFS || DP
easy-and-beginner-friendly-sieve-dfs-dp-kcc8h
Java []\nclass Solution {\n List<Integer>[] adj;\n int cnt[]; long res=0;\n int isprime[];\n private void ini(int n) { //sieve\'s algo\n ispr
Lil_ToeTurtle
NORMAL
2023-09-24T14:04:40.712873+00:00
2023-09-24T14:04:40.712893+00:00
246
false
```Java []\nclass Solution {\n List<Integer>[] adj;\n int cnt[]; long res=0;\n int isprime[];\n private void ini(int n) { //sieve\'s algo\n isprime[1]=1;\n for(int i=2; i<=Math.sqrt(n); i++){\n if(isprime[i]==1) continue;\n for(int j=i+i;j<=n;j+=i){\n isprime[j]=1;\n }\n }\n }\n private boolean isprime(int n) {\n return isprime[n]==0;\n }\n public long countPaths(int n, int[][] edges) {\n adj=new ArrayList[n+1];\n cnt=new int[n];\n isprime=new int[n+1];\n ini(n);\n for(int i=0;i<=n;i++) adj[i]=new ArrayList<Integer>();\n for(int[] e: edges) {\n adj[e[0]].add(e[1]);\n adj[e[1]].add(e[0]);\n }\n \n dfs(1, -1);\n return res;\n }\n private int[] dfs(int node, int paren) {\n int prime1=0, prime0=0; // prime1 is number of path could be formed using 1 prime node, and vice versa for prime0\n if(isprime(node)) prime1++;\n else prime0++;\n\n for(int neigh: adj[node]) {\n if(neigh!=paren) {\n int[] v=dfs(neigh, node); // v0 no prime path, v1 1 prime path\n res+=(long)prime0*v[1];\n res+=(long)prime1*v[0];\n\n if(isprime(node)) prime1+=v[0];\n else prime0+=v[0];\n if(!isprime(node)) prime1+=v[1];\n }\n }\n return new int[]{prime0, prime1};\n }\n}\n```
2
0
['Divide and Conquer', 'Dynamic Programming', 'Java']
2
count-valid-paths-in-a-tree
DFS Tree | Beats 100 percent
dfs-tree-beats-100-percent-by-ultrasonic-p6nu
\n# Approach\n Describe your approach to solving the problem. \nDFS way postorder Tree traversal\n\n- Counting number of distinct paths from node u to all it\'s
UltraSonic
NORMAL
2023-09-24T08:04:11.987521+00:00
2023-09-26T17:17:30.441360+00:00
234
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDFS way postorder Tree traversal\n\n- Counting number of distinct paths from node u to all it\'s children and grandchildren in two buckets - \n bucket-1 : Paths with zero prime-value-node\n bucket-2 : Paths with one prime-value-node\n\nUsing these paths from a node u\n - Finding all paths with one prime-value-node passing via node u (at the same time avoiding duplicate counts)\n - - If node i and j are two child of u \n - - - If node is itself prime, will consider all paths coming from i passing via node u and going to j with zero prime-value-node\n - - - If node is non-prime, Need one-prime path form i and zero-prime paths form j and vice-versa\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nstruct Node{\n long long zeroPrime, onePrime;\n Node(long long z,long long o){\n zeroPrime=z;\n onePrime=o;\n }\n Node(){\n zeroPrime=onePrime=0;\n }\n};\n\nclass Solution {\n\n Node dfs(int u,int pre,long long &ans,vector<vector<int> > &adj, vector<bool> &isPrime){\n \n long long totalZeroPrime=0,totalOnePrime=0;\n Node child;\n for(auto &v:adj[u]){\n if(v!=pre){\n child = dfs(v,u,ans,adj,isPrime);\n if(isPrime[u]){\n // Curr node u is itself prime\n ans+=totalZeroPrime*child.zeroPrime + child.zeroPrime;\n totalZeroPrime+=child.zeroPrime;\n }\n else{\n // Curr node u is not itself a prime\n ans+=totalOnePrime*child.zeroPrime + totalZeroPrime*child.onePrime + child.onePrime;\n totalZeroPrime+=child.zeroPrime;\n totalOnePrime+=child.onePrime;\n }\n }\n }\n \n return isPrime[u]? Node(0,totalZeroPrime+1): Node(totalZeroPrime+1,totalOnePrime);\n }\npublic:\n Solution(){\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n }\n long long countPaths(int &n, vector<vector<int>>& edges) {\n vector<vector<int> > adj(n+1);\n vector<bool> isPrime(n+1,true);\n isPrime[1]=0;\n int j;\n for(int i=2;i<=sqrt(n);i++){\n if(isPrime[i]){\n for(j=2*i;j<=n;j+=i){\n isPrime[j]=false;\n }\n }\n }\n \n for(auto &edge:edges){\n adj[edge[0]].push_back(edge[1]);\n adj[edge[1]].push_back(edge[0]);\n }\n \n long long ans=0;\n dfs(1,0,ans,adj,isPrime);\n \n return ans;\n }\n};\n```
2
0
['Tree', 'Depth-First Search', 'C++']
1
count-valid-paths-in-a-tree
simple dfs, optimized memory usage, concise code
simple-dfs-optimized-memory-usage-concis-muou
\n\n# Approach\n Describe your approach to solving the problem. \n1. using list \'prime\' to record whether the element at index i is a prime or not;\n2. using
akaka54321
NORMAL
2023-09-24T07:36:16.788749+00:00
2023-09-24T07:37:49.559481+00:00
57
false
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. using list \'prime\' to record whether the element at index i is a prime or not;\n2. using dictionary \'g\' to record the edge connection;\n3. with function \'dfs\' to traverse all the edges, it is for sure that all edges will be visited if we started with any edge, as tree is a connected graph. Besides, no duplicated count exists as there is a unique path from any node i to any node j in a tree;\n4. for \'dfs\', we return a list \'v\', with \'v[0]\' denotes the number of path started from node \'curr\' with 0 prime numbers, \'v[1]\' denotes the number of path started from node \'curr\' with 1 prime numbers.\n5. global variable \'res\' is used to sum up all valid paths. \n\n\n\n# Code\n```\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n prime=[1]*(n+1)\n prime[1]=0\n for i in range(2,n+1):\n if prime[i]:\n for j in range(i+i,n+1,i):\n prime[j]=0\n g=defaultdict(list)\n for i,j in edges:\n g[i].append(j)\n g[j].append(i)\n \n def dfs(curr,prev):\n nonlocal res\n v=[1-prime[curr],prime[curr]]\n for nxt in g[curr]:\n if nxt==prev:\n continue\n v_n=dfs(nxt,curr)\n res+=v[0]*v_n[1]+v[1]*v_n[0]\n if prime[curr]:\n v[1]+=v_n[0]\n else:\n v[0]+=v_n[0]\n v[1]+=v_n[1]\n return v\n \n res=0\n dfs(1,0)\n return res\n\n\n\n```
2
0
['Python3']
0
count-valid-paths-in-a-tree
Python Easy To understand , Thought Process
python-easy-to-understand-thought-proces-7qek
Intuition\n Describe your first thoughts on how to solve this problem. \nRequired to separate prime with non prime so used sieve of erastosthenes, build the tre
directioner1d
NORMAL
2023-09-24T04:28:40.689856+00:00
2023-09-24T04:28:40.689879+00:00
97
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRequired to separate prime with non prime so used sieve of erastosthenes, build the tree, noticed that if a non prime makes longest chain of length k containing all non primes then all the k non primes in the chain will also make chain of length k\nfor a prime to make a chain pick 0-k non primes from left and 0-k\' from right non primes (atleast 1 non prime required to call it a chain)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nfirst founded all primes and non primes\nsecond build tree\nthird store in dp the longest chains for any non primes\nfourth for each prime find longest chain multiples right or left\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*(n**0.5))\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n def sieve_of_eratosthenes(n):\n is_prime = [True] * (n + 1)\n is_prime[0] = is_prime[1] = False\n\n for p in range(2, int(n**0.5) + 1):\n if is_prime[p]:\n for i in range(p * p, n + 1, p):\n is_prime[i] = False\n\n primes = [i for i in range(2, n + 1) if is_prime[i]]\n return primes\n prime=set(sieve_of_eratosthenes(n))\n tree={}\n for i,j in edges:\n tree[i]=tree.get(i,set())\n tree[i].add(j)\n tree[j]=tree.get(j,set())\n tree[j].add(i)\n dp={}\n def do(cur):\n cur_vis.add(cur)\n ans=1\n for i in tree.get(cur,[]):\n if(i not in prime and i not in cur_vis):\n ans+=do(i)\n return ans\n cur_vis=set()\n for i in range(1,n+1):\n if(i not in prime and i not in dp):\n cur_vis=set()\n t=do(i)\n for i in cur_vis:\n dp[i]=t\n o=0\n for i in prime:\n s=[]\n crs=0\n for j in tree[i]:\n if(j in prime):\n continue\n s.append(dp[j])\n crs+=dp[j]\n o+=dp[j]\n for i in s:\n crs-=i\n o+=crs*i\n return o\n```
2
0
['Python3']
0
count-valid-paths-in-a-tree
Fun Combinatorics Solution
fun-combinatorics-solution-by-babir-iita
Intuition\nTraverse the tree by dfs, for each node add the number of paths that has the current node as the top node.\n\n# Approach\nWe have to maintain two typ
Babir
NORMAL
2024-10-23T19:26:26.426974+00:00
2024-10-23T19:26:26.427017+00:00
31
false
# Intuition\nTraverse the tree by dfs, for each node add the number of paths that has the current node as the top node.\n\n# Approach\nWe have to maintain two types of paths for each node, where each path only goes upward from some node to the current node.\n1) The number of paths with exactly one node prime\n2) The number of paths with no nodes prime\n\nHow does the transition work for the current node?\nIf the current node is prime\npaths of first type = sum of paths of second type for all children +1\npaths of second type =0;\nif the current node is not prime\npaths of first type = sum of paths of first type for all children\npaths of second type = sum of paths of second type for all children +1\n\nNow how do we combine these points to find the contribution of the current node\nif current node is prime\ntake a path of second type from two distinct subtrees of current node\nif current node is prime \ntake a path of first type from a subtree and take a path of second type from a different subtree\nor just take a path of type 1.\n\n\n# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n $$O(n)$$ \n# Code\n```cpp []\nlong long sol =0;\n#define ll long long \nclass Solution {\npublic:\n void dfs(vector<vector<int>>&g,vector<int>&sieve,vector<ll>&sub,vector<ll> &sub2,int node,int par){\n long long ans1=0,ans2=0;\n long long sos1=0,sos2=0;\n for(auto v:g[node]){\n if(v==par) continue;\n dfs(g,sieve,sub,sub2,v,node);\n ans1+=sub[v];\n ans2+=sub2[v];\n sos1+=(sub[v]*sub[v]);\n sos2+=(sub[v]*sub2[v]);\n }\n if(sieve[node]==2){\n sub[node]=0;\n sub2[node]=1+ans1;\n sol+=(ans1*ans1-sos1)/2;\n sol+=ans1;\n }\n else{\n sub[node]=ans1+1;\n sub2[node]=ans2;\n sol+=ans2;\n sol+=(ans1*ans2-sos2);\n \n }\n \n return;\n\n \n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n sol=0;\n vector<vector<int>> g(n+1);\n for(auto e:edges){\n g[e[0]].push_back(e[1]);\n g[e[1]].push_back(e[0]);\n }\n vector<ll> sub1(n+1,0),sub2(n+1,0);\n vector<int> sieve(n+1,0);\n sieve[1]=1;\n for(int i=2;i<=n;i++ ){\n if(sieve[i]==0){\n sieve[i]=2;\n for(int j =i+i;j<=n;j+=i){\n sieve[j]=1;\n }\n }\n }\n dfs(g,sieve,sub1,sub2,1,1);\n return sol;\n\n }\n};\n```
1
0
['C++']
0
count-valid-paths-in-a-tree
Easy C++ Solution || (Using DFS) Beats 96% ✅✅
easy-c-solution-using-dfs-beats-96-by-ab-94n7
Code\n\nclass Solution {\npublic:\n pair<long,long> helper(vector<int> adj[],int pa,int node,long long &r,vector<bool> &prime){\n pair<long,long> use=
Abhi242
NORMAL
2024-05-02T09:20:10.465318+00:00
2024-05-02T09:20:10.465340+00:00
64
false
# Code\n```\nclass Solution {\npublic:\n pair<long,long> helper(vector<int> adj[],int pa,int node,long long &r,vector<bool> &prime){\n pair<long,long> use={!prime[node],prime[node]};\n for(int a:adj[node]){\n if(a==pa) continue;\n const auto &p=helper(adj,node,a,r,prime);\n r+=(long long)use.first*p.second+ (long long)use.second*p.first;\n if(!prime[node]){\n use.first+=p.first;\n use.second+=p.second;\n }else{\n use.second+=p.first;\n }\n }\n return use;\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<bool> prime(n + 1, true);\n prime[1] = false;\n vector<int> all;\n for (int i = 2; i <= n; ++i) {\n if (prime[i]) {\n all.push_back(i);\n }\n for (int x : all) {\n const int temp = i * x;\n if (temp > n) {\n break;\n }\n prime[temp] = false;\n if (i % x == 0) {\n break;\n } \n }\n }\n vector<int> adj[n+1];\n for(int i=0;i<edges.size();i++){\n adj[edges[i][0]].push_back(edges[i][1]);\n adj[edges[i][1]].push_back(edges[i][0]);\n }\n long long r=0;\n helper(adj,1,1,r,prime);\n return r;\n }\n};\n```
1
0
['Dynamic Programming', 'Tree', 'Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
Sieve + DFS + DP
sieve-dfs-dp-by-karthikeysaxena-5bny
Intuition\n Describe your first thoughts on how to solve this problem. \nDFS + DP + Sieve\n\n# Approach\n Describe your approach to solving the problem. \nFor e
karthikeysaxena
NORMAL
2024-04-16T09:19:21.857591+00:00
2024-04-16T09:19:21.857621+00:00
21
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDFS + DP + Sieve\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each non prime node, we find and store the count of non prime nodes connected to it. The for each prime node, we calculate the number of pair of nodes with current node in the path.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity for sieve - O(n*(log(log(n))))\nTime complexity for 2 DFS traversales - O(2 * n)\n\nHence overall time complexity - O(n*(log(log(n))))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n void sieve(int n, vector<bool> &isPrime) {\n for (int i = 2; (i * i) <= n; i++) {\n if (!isPrime[i]) continue;\n for (int j = (i * i); j <= n; j += i) isPrime[j] = false;\n }\n }\n void dfs(int u, vector<int> &ve, vector<bool> &isPrime, vector<bool> &vis, vector<vector<int>> &adj) {\n vis[u] = true;\n ve.push_back(u);\n for (auto v: adj[u]) {\n if (!isPrime[v] && !vis[v]) dfs(v, ve, isPrime, vis, adj);\n }\n }\n long long countPaths(int n, vector<vector<int>>& e) {\n vector<vector<int>> adj(n + 1);\n for (auto x: e) {\n adj[x[0]].push_back(x[1]);\n adj[x[1]].push_back(x[0]);\n }\n\n vector<bool> isPrime(n + 1, true), vis(n + 1, false);\n isPrime[1] = false;\n sieve(n, isPrime);\n\n vector<int> c(n + 1);\n for (int i = 1; i <= n; i++) {\n if (!isPrime[i] && !vis[i]) {\n vector<int> v;\n dfs(i, v, isPrime, vis, adj);\n for (auto x: v) c[x] = v.size();\n }\n }\n\n long long ans = 0;\n for (int i = 1; i <= n; i++) {\n if (!isPrime[i]) continue;\n vector<int> v;\n long long s = 0;\n for (auto j: adj[i]) {\n if (isPrime[j]) continue;\n v.push_back(c[j]);\n s += c[j];\n }\n ans += s;\n for (auto x: v) {\n s -= x;\n ans += (x * s);\n }\n }\n\n return ans;\n }\n};\n```
1
0
['C++']
0
count-valid-paths-in-a-tree
rerooting + dp
rerooting-dp-by-abhijith89-o1qt
Intuition\n Tree rerooting\n\n# Complexity\n- Time complexity:\n O(nlog(logn)) + O(n)\n\n- Space complexity:\n O(n)\n\n# Code\n\nclass Solution {\npublic:\n
abhijith89
NORMAL
2024-02-06T06:42:38.620322+00:00
2024-02-06T06:42:38.620393+00:00
28
false
# Intuition\n Tree rerooting\n\n# Complexity\n- Time complexity:\n O(nlog(logn)) + O(n)\n\n- Space complexity:\n O(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>>g;\n vector<int>prime;\n vector<long long> child,cnt;\n long long ans=0;\n void seive(int n){\n prime[0]=0;\n prime[1]=0;\n for(int i=2;i*i<=n;i++){\n if(prime[i]==0)continue;\n for(int j=i*i;j<=n;j+=i){\n prime[j]=0;\n }\n }\n }\n void dfs(int u , int par=-1){\n if(!prime[u])child[u]=1;\n else child[u]=0;\n for(int v:g[u]){\n if(v==par)continue;\n dfs(v,u);\n if(!prime[u])child[u]+=child[v];\n else cnt[u]+=child[v];\n }\n }\n void reroot(int u , int par=-1 , long long to=0){\n if(prime[u])cnt[u]+=to;\n for(int v:g[u]){\n if(v==par)continue;\n if(!prime[u])reroot(v,u,to+child[u]-child[v]);\n else reroot(v,u,0ll);\n }\n }\n void dfs1(int u , int par=-1){\n if(prime[u]){\n int sum2=cnt[u];\n for(int v:g[u]){\n if(v==par)continue;\n sum2-=child[v];\n ans+=(child[v]*sum2);\n }\n ans+=(cnt[u]);\n }\n for(int v:g[u]){\n if(v==par)continue;\n dfs1(v,u);\n }\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n prime.assign(n+1,1);\n child.resize(n+1);\n cnt.assign(n+1,0);\n g.resize(n+1);\n seive(n);\n for(vector<int> v:edges){\n g[v[0]].push_back(v[1]);\n g[v[1]].push_back(v[0]);\n }\n dfs(1);\n reroot(1);\n dfs1(1);\n return ans;\n }\n};\n```
1
0
['C++']
0
count-valid-paths-in-a-tree
C++ Solution - Like DSU (more like bruteforce)
c-solution-like-dsu-more-like-bruteforce-iccx
Intuition\nSee, we have to find paths which are having only 1 prime number, so, for all prime number nodes, if we are able to find pool of non prime nodes count
kingsman007
NORMAL
2023-10-23T07:48:02.219877+00:00
2023-10-23T07:50:23.615512+00:00
71
false
# Intuition\nSee, we have to find paths which are having only 1 prime number, so, for all prime number nodes, if we are able to find pool of non prime nodes count which are connected to it, we can easiely find answer for that node using permutations. Say, for a prime node, three connected components of non prime nodes of count say a, b, c are connected. \nSo, for that prime node, answer will have (a + b + c) part taking 1 node of any of those and 1 of our prime node, and second, if we take both from a, b, c parts, so for that, we will add to our answer (a + b) * c + (a + c) * b + (c + b) * a. \n\nThis process we will repeat for each prime node. \nSo, all functions in code are used for: \n\n1. isPrime() - using sieve method to find all prime and store in isPrime\n2. bfs() - to mark a pool or connected part of non - primes with pool unique number and return size of pool\n3. findAns() - find answer for each prime node, as described before\n4. countPath() - main function to make adjacency list, call all above functions, assign pool using bfs and mapping its size to a map poolCount, then finding answer for all prime nodes.\n\n# Code\n```\nclass Solution {\nprivate:\n bool isPrime[100001];\n unordered_map<int, int> poolCount;\n // checks and store state of all prime numbers\n void preCum() {\n isPrime[0] = isPrime[1] = false;\n for(int i = 2; i * i < 100001; i++) {\n if(isPrime[i]) {\n for(int j = i * i; j < 100001; j += i) {\n isPrime[j] = false;\n }\n }\n }\n }\n // mark all non - prime nodes\n int bfs(vector<int> adj[], vector<int>& pool, vector<bool>& vis, int n, int s, int poolNo) {\n queue<int> q;\n q.push(s);\n vis[s] = true;\n pool[s] = poolNo;\n int ret = 1;\n while(!q.empty()) {\n int t = q.front();\n q.pop();\n for(int u: adj[t]) {\n if(!isPrime[u] and !vis[u]) {\n q.push(u);\n vis[u] = true;\n pool[u] = poolNo;\n ret++;\n }\n }\n }\n return ret;\n }\n // finds no. of paths possible for a prime node\n long long findAns(unordered_set<int> s) {\n long long sum = 0;\n long long ret = 0;\n for(int i: s) {\n sum += poolCount[i];\n }\n for(int i: s) {\n ret += poolCount[i] * (sum - poolCount[i]);\n }\n ret /= 2;\n ret += sum;\n return ret;\n }\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n // constructing adjacency list\n vector<int> adj[n + 1];\n for(auto& e: edges) {\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n // find whether prime or not using sieve method\n memset(isPrime, 1, sizeof(isPrime));\n preCum();\n // like alotting a pool number to edges\n // it can be done by making a pool array with unique id and map from id to size\n vector<int> pool(n + 1, -1);\n vector<bool> vis(n + 1, false);\n int poolNo = 1;\n for(int i = 1; i <= n; i++) {\n if(!isPrime[i] and !vis[i]) {\n int c = bfs(adj, pool, vis, n, i, poolNo);\n poolCount[poolNo] = c;\n poolNo++;\n }\n }\n // now, for every prime node just finding answer\n long long ret = 0;\n for(int i = 1; i <= n; i++) {\n if(pool[i] == -1) {\n unordered_set<int> nonPrimePool;\n for(int& u: adj[i]) {\n if(pool[u] != -1)\n nonPrimePool.insert(pool[u]);\n }\n ret += findAns(nonPrimePool);\n }\n }\n return ret;\n }\n};\n```
1
0
['Breadth-First Search', 'C++']
1
count-valid-paths-in-a-tree
Rust/Python. Almost linear time with detailed explanation. Beats 100%
rustpython-almost-linear-time-with-detai-4pa9
Intuition\n\nYou can easily see that you do not care about values in the tree, the only thing you care is whether the node is prime or no. So we can just consid
salvadordali
NORMAL
2023-09-26T00:08:51.318869+00:00
2023-09-26T00:08:51.318888+00:00
10
false
# Intuition\n\nYou can easily see that you do not care about values in the tree, the only thing you care is whether the node is prime or no. So we can just consider the graph with only zeros (not-primes) and ones (primes). I will ignore the part how to find whether something is prime (the most efficient is to implemetn [sieve](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)) and building a tree (it is obvious). See `eratosthenes_sieve` and `build_graph`.\n\n\nNow rephrasing the problem as a tree with `0, 1` nodes the question asks how many pathes are their in a tree whose sum is exactly 1. \n\nWe can calculate this value by noticing that we can look at any specific node and checking how many of such pathes are going via this node. To get a path with exactly sum of exactly one we need to know two values:\n - how many pathes have sum of zero. I call them `n0, num0` in code\n - how many pathes have sum of exactly one. I call them `n1, num1` in code.\n\nThe only way to create path of sum one is to combine each path in `n0` with each pathe with `n1` (basically multiply them).\n\nNow lets assume that we have a function which returns those two values. For leaf nodes it will be `(1, 0)` if the node is not prime and `(0, 1)` for prime nodes. Lets see are you going to update the values and the results based on child nodes.\n\n---------------\n\nLets look at the situation where parent is `1` and has some children. We know that we return `(0, num1)` in this case (as it is not possible to be path of sum 0), and we start `num1 = 1` (we already have soem path). Here where we get `n0, n1 = dfs(...)` and use them to update res += `n0 * num1` (already explained why) and update the number of pathes which currently have at most one will be updated by `n0` (as we already have 1)\n\n\n-------------\n\nLets look at the situation where parent is `1` and has some children. Here we might have both values and we start from `num0, num1 = 1, 0`. Having `n0, n1 = dfs(...)` we do the updates:\n - `res` by both components `n0 * num1 + n1 * num0`\n - `num0 += n0`. Because the parent is 0, we just increase by `n0`\n - `num1 += n1`. Because the parent is 0, we just increase by `n1`\n\n\n\n# Complexity\n- Time complexity: $O(n \\log \\log n)$\n- Space complexity: $O(n)$\n\n# Code\n\nNotice that in Rust I return 3 values where first is the result. We can do the same in Py, but there it seemed to me that having class variables is easier.\n\n```Rust []\nimpl Solution {\n\n fn eratosthenes_sieve(n: usize) -> Vec<bool> {\n let (mut primes, mut res) = (vec![true; n], vec![2]);\n let mut is_prime = vec![false; n];\n if 2 < is_prime.len() {\n is_prime[2] = true;\n }\n let sqrt_n = ((n as f64).sqrt() as usize + 1) | 1;\n for p in (3 .. sqrt_n).step_by(2) {\n if primes[p] {\n is_prime[p] = true;\n for i in (p * p .. n).step_by(2 * p) {\n primes[i] = false;\n }\n }\n }\n\n for p in (sqrt_n .. n).step_by(2) {\n if primes[p] {\n is_prime[p] = true;\n }\n } \n\n return is_prime;\n }\n\n fn build_graph(edges: Vec<Vec<i32>>) -> Vec<Vec<usize>> {\n let mut g = vec![Vec::new(); edges.len() + 2];\n for v in edges {\n g[v[0] as usize].push(v[1] as usize);\n g[v[1] as usize].push(v[0] as usize);\n }\n\n return g;\n }\n\n fn dfs(node: usize, node_parent: usize, g: &Vec<Vec<usize>>, is_prime: &Vec<bool>) -> (i64, i64, i64) {\n let mut res = 0i64;\n\n if is_prime[node] {\n let mut num1 = 1i64;\n for i in 0 .. g[node].len() {\n let node_nxt = g[node][i];\n if node_nxt == node_parent {\n continue\n }\n\n let (r, n0, n1) = Self::dfs(node_nxt, node, g, is_prime);\n res += r + num1 * n0;\n num1 += n0;\n }\n return (res, 0, num1);\n }\n\n let (mut num0, mut num1) = (1i64, 0i64);\n for i in 0 .. g[node].len() {\n let node_nxt = g[node][i];\n if node_nxt == node_parent {\n continue\n }\n\n let (r, n0, n1) = Self::dfs(node_nxt, node, g, is_prime);\n res += r + n0 * num1 + n1 * num0;\n num0 += n0;\n num1 += n1;\n }\n return (res, num0, num1);\n }\n\n pub fn count_paths(n: i32, edges: Vec<Vec<i32>>) -> i64 {\n let is_prime = Self::eratosthenes_sieve(n as usize + 1);\n let g = Self::build_graph(edges);\n\n let (r, n1, n2) = Self::dfs(1, 0, &g, &is_prime);\n return r;\n }\n}\n```\n```python []\nclass Solution:\n\n def __init__(self):\n self.primes = []\n self.g = []\n self.res = 0\n\n def eratosthenes_sieve(self, n):\n prime, result, sqrt_n = [True] * n, {2}, (int(n ** .5) + 1) | 1 # ensure it\'s odd\n for p in range(3, sqrt_n, 2):\n if prime[p]:\n result.add(p)\n prime[p * p::2 * p] = [False] * ((n - p * p - 1) // (2 * p) + 1)\n\n self.primes = result | {p for p in range(sqrt_n, n, 2) if prime[p]}\n\n def build_graph(self, edges):\n g = [[] for _ in range(len(edges) + 2)]\n for v1, v2 in edges:\n g[v1].append(v2)\n g[v2].append(v1)\n self.g = g\n\n def dfs(self, node, node_parent):\n if node in self.primes:\n num1 = 1\n for node_nxt in self.g[node]:\n if node_nxt == node_parent:\n continue\n\n n0, n1 = self.dfs(node_nxt, node)\n self.res += n0 * num1\n num1 += n0\n return 0, num1\n \n num0, num1 = 1, 0\n for node_nxt in self.g[node]:\n if node_nxt == node_parent:\n continue\n\n n0, n1 = self.dfs(node_nxt, node)\n self.res += num0 * n1 + num1 * n0\n num1 += n1\n num0 += n0\n \n return num0, num1\n\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n self.eratosthenes_sieve(n + 3)\n self.build_graph(edges)\n self.dfs(1, -1)\n return self.res\n```\n
1
0
['Python', 'Rust']
0
count-valid-paths-in-a-tree
DFS/DP + Sieve of Eratosthenes. beats 99% time 100% memory. With clear comments in code.
dfsdp-sieve-of-eratosthenes-beats-99-tim-i7ca
Intuition\n Describe your first thoughts on how to solve this problem. \nUsually for problem related to ALL PATH IN TREE, we can use DFS.\n# Approach\n Describe
DongmingShen
NORMAL
2023-09-25T03:59:36.883440+00:00
2023-09-25T03:59:36.883465+00:00
591
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsually for problem related to ALL PATH IN TREE, we can use DFS.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBefore solving the question, to effectively check prime, we need a prime tester => Sieve of Eratosthenes (Google it if don\'t know).\n\nNow, we can see that all possible PATH IN TREE have the same form: for any node in the tree: [node\'s chain i] + node + [node\'s chain j] where i != j forms a path. Therefore if we count NUM OF PATH (with exactly 1 prime) for all nodes we will get the solution. \n\nIn order to do compute this, we need three information for each node:\n1. for each child node: number of chains ending at child containing 0 prime\n2. for each child node: number of chains ending at child containing 1 prime\n3. number of valid path with peak at node (Note that the sum of all this gives the result)\n\nMORE information can be found in the comments in my code!\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# To effectively check prime, we need a prime tester => Sieve of Eratosthenes (Google it if don\'t know)\n# We put this here because Leetcode only do this part once for all solutions so we can reuse and save some time\ndef getAllPrimes():\n n = 10 ** 5\n prime = [True for _ in range(n + 1)]\n prime[0] = prime[1] = False\n x, y = 2, int(sqrt(n)) + 1\n while x < y:\n if prime[x]: \n for i in range(x * 2, n + 1, x):\n prime[i] = False\n x += 1\n return prime \nprimes = getAllPrimes() # primes[number] = True if prime, False otherwise\n\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n # all possible PATH = [node\'s one chain] + node peak + [node\'s another chain] \n # for each node we need three informations:\n # 1. for each child node: number of chains contains 0 prime\n # 2. for each child node: number of chains contains 1 prime\n # 3. number of valid PATH with peak at node => sum for all nodes will give us result\n # get all neighbors\n neighbors = [[] for _ in range(n + 1)]\n for u, v in edges:\n neighbors[u].append(v)\n neighbors[v].append(u)\n # define dfs that will help us collect the three informations & update result\n result = [0]\n visited = dict()\n def dfs(node, prev):\n visited[node] = 0\n # Step1: get info from child nodes\n allChain0s, allChain1s = [], []\n total0, total1 = 0, 0\n for child in neighbors[node]:\n # since we have a undirected tree, to avoid inf-loop, we need to ignore visited states\n if child == prev: continue\n chain0, chain1 = dfs(child, node)\n total0 += chain0\n total1 += chain1\n allChain0s.append(chain0) \n allChain1s.append(chain1)\n # Step2: combine to create new info for the current node\n # current node is prime\n if primes[node]: \n # 1. all chains ending at node will have >0 prime\n currChain0 = 0 \n # 2. 1 (itself) + all previous 0-chains ending at node will have 1 prime\n currChain1 = 1 + total0\n # 3. node as peak combine with any 0 chains is valid\n combTotal = 0\n for tmp0 in allChain0s: # count combinations of two 0 chains from different childs\n combTotal += (tmp0 * (total0 - tmp0))\n result[0] += (total0 + combTotal // 2)\n # current node is not prime\n else:\n # 1. chains ending at node will have 0 prime IFF the original chain contain 0 prime\n currChain0 = 1 + total0\n # 2. chains ending at node will have 1 prime IFF the original chain contain 1 prime\n currChain1 = total1\n # 3. node as peak combine with single 1 chain OR 1x1chain + 1x0chain at different childs is valid\n combTotal = 0\n for i in range(len(allChain0s)): # count combinations of 1x1chain + 1x0chain from different childs\n tmp0, tmp1 = allChain0s[i], allChain1s[i]\n combTotal += (tmp0 * (total1 - tmp1)) + (tmp1 * (total0 - tmp0))\n result[0] += (total1 + combTotal // 2)\n return currChain0, currChain1\n dfs(1, inf)\n return result[0]\n\n\n \n```
1
0
['Math', 'Dynamic Programming', 'Tree', 'Depth-First Search', 'Graph', 'Python3']
0
count-valid-paths-in-a-tree
Python/C++, dfs solution with explanation
pythonc-dfs-solution-with-explanation-by-218s
dfs\n\n\n\nwe can eunmerate each prime node,\nand count valid paths will pass through this node,\nso, we should node size of connected component consit of non-p
shun6096tw
NORMAL
2023-09-24T09:47:40.477594+00:00
2023-09-25T08:16:50.524723+00:00
214
false
### dfs\n\n![image](https://assets.leetcode.com/users/images/03d39b63-60db-466e-9d18-ee14c24c577c_1695629809.6104665.png)\n\nwe can eunmerate each prime node,\nand count valid paths will pass through this node,\nso, we should node size of connected component consit of non-prime nodes connect to this node,\nthe nodes in connected component can be a start or end node of valid path.\n\nWe can use dfs to count size of connected component, and record it to a array to reuse.\n\ntc is O(n), sc is O(n).\n\n\n### python\n```python\n# sieve \n\nMX = int(1e5) + 1\nis_prime = [True] * MX\nis_prime[1] = False\nfor i in range(2, isqrt(MX) + 1):\n if is_prime[i]:\n for j in range(i * i, MX, i):\n is_prime[j] = False\n\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n g = [[] for _ in range(n+1)]\n for x, y in edges:\n g[x].append(y)\n g[y].append(x)\n \n node = []\n def dfs(cur, prev):\n node.append(cur)\n for nei in g[cur]:\n if is_prime[nei] == False and nei != prev:\n dfs(nei, cur)\n \n size = [0] * (n+1)\n ans = 0\n for i in range(1, n+1):\n\t\t\t# eunmerate each prime node\n if is_prime[i] == False: continue\n s = 0 # total size of conected component consit of non-prime nodes\n for j in g[i]: # check if any connected component consit of non-prime nodes connect to this prime node\n if is_prime[j]: continue # skip prime node\n if size[j] == 0: # this node has not been visited\n node.clear()\n dfs(j, -1)\n for x in node: # nodes of connected component\n size[x] = len(node) # size of connected component\n ans += size[j] * s # Start from a non-prime node and end at a non-prime node\n s += size[j] # Start from a prime node and end at a non-prime node\n ans += s\n return ans\n```\n\n### c++\n```cpp\nconst int MX = 1e5;\nbool not_prime[MX+1];\nint init = [] () {\n not_prime[1] = true;\n for (int i = 2; i * i <= MX; i+=1) {\n if (!not_prime[i]) {\n for (int j = i*i; j <= MX; j+=i)\n not_prime[j] = true;\n }\n }\n return 0;\n}();\n\nclass Solution {\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<vector<int>> g (n+1);\n for (auto& e: edges) {\n g[e[0]].emplace_back(e[1]);\n g[e[1]].emplace_back(e[0]);\n }\n long long ans = 0;\n vector<int> size (n+1);\n vector<int> node;\n function<void(int, int)> dfs = [&] (int cur, int prev) {\n node.emplace_back(cur);\n for (auto& nei: g[cur]) {\n if (not_prime[nei] && nei != prev)\n dfs(nei, cur);\n }\n };\n for (int i = 1, s; i <= n; i+=1) {\n if (not_prime[i]) continue;\n s = 0;\n for (auto& j: g[i]) {\n if (not_prime[j] == false) continue;\n if (size[j] == 0) {\n node.clear();\n dfs(j, -1);\n for (auto& x: node)\n size[x] = node.size();\n }\n ans += 1LL * s * size[j];\n s += size[j];\n }\n ans += s;\n }\n return ans;\n }\n};\n```
1
0
['Math', 'Depth-First Search', 'C', 'Python']
0
count-valid-paths-in-a-tree
Rerooting of Tree + underStanding of maths. + sieve algo
rerooting-of-tree-understanding-of-maths-vwde
Intuition\n Describe your first thoughts on how to solve this problem. \n- we have to calculate the answer of number of path from each of the node which are pri
aryan20022003
NORMAL
2023-09-24T07:09:25.972916+00:00
2023-09-24T07:09:25.972944+00:00
434
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- we have to calculate the answer of number of path from each of the node which are prime \n- For that we need to know the wheather the provided node is prime or not so we can precompute the using sieve algo\n- now let say I know the answer of perticular node which is prime what all thing do i need to know.\n1. I need to know number of nodes below it which are not prime in contiguous manner \n2. we can calulate that through dfs1 .\n3. now let say out node has 4 branch and from each we get a,b,c, child node which are not prime and contiguous \n4. now for that node answer will be ab+bc+ca +a+b+c possible ways \n5. mathematically ((a+b+c)^2 -a^2-b^2-c^2)/2 + (b+a+c)\n6. now this is for each prime node provided we will only consider child subTrees\n7. Now once we calcualted for each child we just have to use the concept of rerotting and shift the root and calulate the answer from each prime node where they will **take one node from below and one node from above**\n8. Keep in mind we are only looking for non prime node from below on dfs1 and non prime node contribution by parent in dfs2\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- time complexity $$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n set<int>prime;\n long long FinalAnswer;\n set<int> sieveOfEratosthenes(int n) {\n std::vector<bool> isPrime(n + 1, true);\n std::set<int> primes;\n\n isPrime[0] = isPrime[1] = false; // 0 and 1 are not prime\n\n for (int p = 2; p * p <= n; ++p) {\n if (isPrime[p]) {\n for (int i = p * p; i <= n; i += p) {\n isPrime[i] = false;\n }\n }\n }\n\n for (int i = 2; i <= n; ++i) {\n if (isPrime[i]) {\n primes.insert(i);\n }\n }\n\n return primes;\n }\n \n int dfs1(int node,int parent,vector<int>adj[],vector<int>&record)\n {\n int total=0;\n int subTotal=0;\n for(auto &it:adj[node])\n {\n if (it==parent)\n {\n continue;\n }\n else\n { \n long long tempTotal=dfs1(it,node,adj,record);\n total+=tempTotal;\n subTotal+=tempTotal*tempTotal;\n }\n }\n record[node]=total;\n if (prime.find(node)!=prime.end())\n {\n FinalAnswer+=(total*1ll*total-subTotal)/2;\n FinalAnswer+=total;\n return 0;\n }\n return total+1;\n }\n void dfs2(int node,int parent,vector<int>adj[],vector<int>&record,vector<int>&up)\n {\n bool flag=0;\n if (prime.find(node)!=prime.end())\n {\n // cout<<node<<" "<<record[node]+up[node]<<"\\n";\n FinalAnswer+=up[node]+up[node]*record[node];\n flag=1;\n }\n for(auto &it:adj[node])\n {\n if (it==parent)\n {\n continue;\n }\n if (flag==1)\n {\n up[it]=0;\n dfs2(it,node,adj,record,up);\n }\n else if (prime.find(it)!=prime.end())\n {\n up[it]=record[node]+1+up[node];\n dfs2(it,node,adj,record,up);\n }\n else \n {\n up[it]=up[node]+record[node]-record[it];\n dfs2(it,node,adj,record,up);\n }\n }\n \n }\n \n long long countPaths(int n, vector<vector<int>>& edges) \n {\n prime=sieveOfEratosthenes(n);\n vector<int>adj[n+1];\n for(auto &it:edges)\n {\n adj[it[0]].push_back(it[1]);\n adj[it[1]].push_back(it[0]);\n }\n FinalAnswer=0;\n vector<int>record(n+1,0);\n dfs1(1,0,adj,record);\n // for(auto &it:record)\n // {\n // cout<<it<<" ";\n // }\n // cout<<"\\n";\n // cout<<FinalAnswer<<"\\n";\n vector<int>up(n+1,0);\n dfs2(1,0,adj,record,up);\n return FinalAnswer;\n }\n};\n```
1
0
['Math', 'Tree', 'Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
JAVA DP ON TREES || EASY SOLUTION
java-dp-on-trees-easy-solution-by-akash0-cc7x
\nclass Solution {\n public long countPaths(int n, int[][] edges) {\n long dp[][]=new long[n+1][3];\n ArrayList<ArrayList<Integer>> child=new A
akash0228
NORMAL
2023-09-24T05:23:52.281397+00:00
2023-09-24T05:23:52.281427+00:00
162
false
```\nclass Solution {\n public long countPaths(int n, int[][] edges) {\n long dp[][]=new long[n+1][3];\n ArrayList<ArrayList<Integer>> child=new ArrayList<>();\n \n for(int i=0;i<=n;i++){\n child.add(new ArrayList<>());\n }\n \n for(int i=0;i<n-1;i++){\n int par=edges[i][0];\n int c=edges[i][1];\n child.get(par).add(c);\n child.get(c).add(par);\n }\n \n HashSet<Integer> set=new HashSet<>();\n sieveOfEratosthenes(set);\n \n solve(1,0,child,dp,set);\n \n return dp[1][2]; \n }\n \n public void sieveOfEratosthenes(HashSet<Integer> set) {\n boolean[] flag = new boolean[100000];\n\t\t\tfor (int i = 2; i < flag.length; i++) {\n\t\t\t\tif (!flag[i]) {\n\t\t\t\t\tset.add(i);\n\t\t\t\t\tfor (int j = i; j < flag.length; j += i) {\n\t\t\t\t\t\tflag[j] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n }\n \n \n public void solve(int src,int par,ArrayList<ArrayList<Integer>> child,long dp[][],HashSet<Integer> set){ \n if(set.contains(src)){\n dp[src][1]=1;\n dp[src][0]=0;\n }\n else{\n dp[src][0]=1;\n dp[src][1]=0;\n }\n \n for(int next:child.get(src)){\n if(next==par)\n continue;\n \n solve(next,src,child,dp,set);\n \n //this prime\n dp[src][2]=dp[src][2]+dp[next][2]+dp[src][0]*dp[next][1]+dp[src][1]*dp[next][0];\n \n if(set.contains(src)){\n dp[src][1]+=dp[next][0];\n }\n else{\n dp[src][0]+=dp[next][0];\n dp[src][1]+=dp[next][1];\n } \n }\n \n }\n \n}\n```
1
0
['Dynamic Programming', 'Tree', 'Java']
1
count-valid-paths-in-a-tree
C# Union-Find + Math Theory
c-union-find-math-theory-by-enze_zhang-iw06
Code\n\npublic class Solution {\n Dictionary<int, int> map = new();\n const int N = (int)1e5 + 10, M = N * 2;\n int[] h = new int[N], e = new int[M], n
enze_zhang
NORMAL
2023-09-24T04:32:58.427829+00:00
2023-09-24T04:32:58.427864+00:00
35
false
# Code\n```\npublic class Solution {\n Dictionary<int, int> map = new();\n const int N = (int)1e5 + 10, M = N * 2;\n int[] h = new int[N], e = new int[M], ne = new int[M];\n int[] cr = new int[N], node = new int[N];\n int idx = 0;\n \n public long CountPaths(int n, int[][] edges) {\n Sieve(n + 1);\n for(int i = 0; i <= n + 1; i++){\n h[i] = -1;\n cr[i] = 1;\n node[i] = i;\n }\n for(int i = 0; i < edges.Length; i++){\n int u = edges[i][0], v = edges[i][1];\n Build(u, v);\n Build(v, u);\n }\n \n Dfs(2, 2);\n long owo = 0;\n foreach(var kvp in map){\n int u = kvp.Key;\n if(u > n) break;\n long qaq = 0, uwu = 0;\n for(int i = h[u]; i != -1; i = ne[i]){\n if(map.ContainsKey(e[i])) continue;\n else{\n qaq = uwu * cr[node[e[i]]];\n uwu += cr[node[e[i]]];\n owo += qaq;\n }\n }\n owo += uwu;\n }\n return owo;\n }\n \n public void Dfs(int u, int fa){\n for(int i = h[u]; i != -1; i = ne[i]){\n int j = e[i];\n if(j == fa) continue;\n if(!map.ContainsKey(u) && !map.ContainsKey(j)){\n cr[Find(u)] += cr[Find(j)];\n node[Find(j)] = Find(u); \n }\n Dfs(j, u);\n }\n }\n \n public int Find(int x){\n return x == node[x] ? x : node[x] = Find(node[x]);\n }\n \n public void Build(int u, int v){\n e[idx] = v; ne[idx] = h[u]; h[u] = idx++;\n }\n \n public void Sieve(int n){\n int[] p = new int[n + 1];\n List<int> primes = new();\n for(int i = 2; i < n; i++){\n if((p[i] & 1) == 0){\n p[i]++;\n map[i] = 1;\n primes.Add(i);\n }\n foreach(var pr in primes){\n if(pr * i > n) break;\n p[pr * i]++;\n if(i % pr == 0) break;\n }\n }\n }\n}\n```
1
0
['C#']
0
count-valid-paths-in-a-tree
[Python] Only use BFS
python-only-use-bfs-by-m2h1b8-sxqj
\n# Code\n\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n if n <= 2:\n return n - 1\n G = default
m2h1b8
NORMAL
2023-09-24T04:26:30.920735+00:00
2023-09-24T04:28:41.755039+00:00
59
false
\n# Code\n```\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n if n <= 2:\n return n - 1\n G = defaultdict(list)\n for a, b in edges:\n G[a].append(b)\n G[b].append(a)\n \n isPrime = [1] * (n + 1)\n isPrime[0], isPrime[1] = 0, 0\n for i in range(2, n + 1):\n if isPrime[i] == 0:\n continue\n j = i * 2\n while j <= n:\n isPrime[j] = 0\n j += i\n\n ans = 0\n count = defaultdict(lambda: 1)\n visited = set()\n for i in range(1, n + 1):\n if isPrime[i]:\n continue\n if i in visited:\n continue\n c = 1\n visited.add(i)\n queue = deque([i])\n primes = []\n while queue:\n node = queue.popleft()\n for nxt in G[node]:\n if isPrime[nxt]:\n primes.append(nxt)\n continue\n if nxt in visited:\n continue\n c += 1\n visited.add(nxt)\n queue.append(nxt)\n for p in primes:\n ans += c * count[p]\n count[p] += c\n return ans\n \n \n\n```
1
0
['Breadth-First Search', 'Python3']
0
count-valid-paths-in-a-tree
Simple cpp solution with explanation
simple-cpp-solution-with-explanation-by-6vczg
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Code_Of_Duty
NORMAL
2023-09-24T04:10:08.776560+00:00
2023-09-24T04:10:08.776590+00:00
148
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // Function to generate a vector of boolean values where prime[i] is true if \'i\' is prime.\n vector<bool> genPrimes(int n) {\n vector<bool> prime(n + 1);\n \n // Initialize all numbers as potential prime numbers (true).\n if (n > 1) fill(prime.begin() + 2, prime.end(), true);\n \n // Sieve of Eratosthenes algorithm: Mark multiples of each prime number as non-prime.\n for (int i = 2; i <= n; ++i)\n if (prime[i])\n for (int j = i + i; j <= n; j += i)\n prime[j] = false;\n \n return prime;\n }\n \n // Function to count paths in a tree graph where some nodes are prime and others are not.\n long long countPaths(int n, vector<vector<int>>& edges) {\n // Generate a vector to store whether each node is prime.\n auto isPrime = genPrimes(n);\n \n // Create an adjacency list representation of the tree.\n vector<vector<int>> E(n);\n for (int i = 0; i < n - 1; ++i) {\n int u = edges[i][0], v = edges[i][1];\n --u;\n --v;\n E[u].push_back(v);\n E[v].push_back(u);\n }\n \n long long ans = 0;\n \n // Define a recursive DFS (Depth-First Search) function.\n function<array<int, 2>(int, int)> dfs = [&](int x, int p) {\n int prime = isPrime[x + 1];\n array<int, 2> cur = {};\n cur[prime]++;\n \n // Recursively traverse the tree.\n for (int y : E[x]) {\n if (y == p) continue;\n auto v = dfs(y, x);\n ans += (long long)v[0] * cur[1];\n ans += (long long)v[1] * cur[0];\n cur[prime] += v[0];\n \n // If the current node is not prime, update the count for prime nodes.\n if (!prime) cur[1 + prime] += v[1];\n }\n \n return cur;\n };\n \n // Start DFS from the root node (node 0) with parent -1.\n dfs(0, -1);\n \n return ans;\n }\n};\n\n```
1
0
['Math', 'Dynamic Programming', 'Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
Math + Components of non-prime nodes
math-components-of-non-prime-nodes-by-ce-6vwl
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can change our perspectives a bit to make this problem easier: for every node that i
CelonyMire
NORMAL
2023-09-24T04:06:32.371284+00:00
2023-09-24T04:06:32.371308+00:00
155
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can change our perspectives a bit to make this problem easier: **for every node that is a prime number, how many pairs of nodes of different "components" of the prime node can we make"?\n\nHere we define a component as a group of directly connected nodes that are not prime.\n\n![Untitled.png](https://assets.leetcode.com/users/images/116b4fd6-cf32-4214-b3bc-f5285fedf48d_1695528217.809653.png)\n\n\nThe prime nodes are underlined in red, and we can visually see all the adjacent nodes that are not a prime is treated as a component with the orange border.\n\nNow all we have to do is count the answer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can use **Union-Find** to unite all the adjacent non-prime nodes to identify our components as well as how many nodes exist within a component. Then it is a matter of counting correctly (see code for details)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nstruct DSU {\n vector<int> parent, size;\n DSU(int n) : parent(n), size(n, 1) { iota(parent.begin(), parent.end(), 0); }\n int find(int i) {\n if (parent[i] == i)\n return i;\n return parent[i] = find(parent[i]);\n }\n void unite(int i, int j) {\n if (find(i) != find(j)) {\n int repi = find(i);\n int repj = find(j);\n if (size[repi] < size[repj])\n swap(repi, repj);\n size[repi] += size[repj];\n parent[repj] = repi;\n }\n }\n};\n\nstruct sieve {\n vector<int> primes, composite, sd;\n sieve(int n) : composite(n + 1), sd(n + 1) {\n sd[1] = 1;\n composite[1] = true;\n for (int i = 2; i <= n; i++) {\n if (!composite[i]) {\n primes.push_back(i);\n sd[i] = i;\n }\n for (int j = 0; j < primes.size() && i * primes[j] <= n; j++) {\n composite[i * primes[j]] = true;\n sd[i * primes[j]] = primes[j];\n if (i % primes[j] == 0)\n break;\n }\n }\n }\n};\n\nclass Solution {\npublic:\n long long countPaths(int n, vector<vector<int>> &edges) {\n vector<vector<int>> g(n + 1);\n for (auto &e : edges) {\n g[e[0]].push_back(e[1]);\n g[e[1]].push_back(e[0]);\n }\n DSU dsu(n + 1);\n sieve sv(n); // for primes in range [1, n] and checking if number is a prime\n for (auto &e : edges) {\n if (sv.composite[e[0]] && sv.composite[e[1]]) {\n dsu.unite(e[0], e[1]); // both the nodes in the edges are non-prime, unite them\n }\n }\n long long ans = 0;\n for (int u : sv.primes) {\n long long x = 0; // the total number of nodes in adjacent components\n for (int v : g[u]) {\n if (!sv.composite[v])\n continue;\n x += dsu.size[dsu.find(v)];\n }\n long long cur = 0;\n for (int v : g[u]) {\n if (!sv.composite[v])\n continue;\n long long k = dsu.size[dsu.find(v)];\n cur += k * (x - k); // number of pairs from component with node "v" to nodes in the other component\n }\n cur /= 2; // remove duplicate pairs here, we\'re adding unique pairs below\n for (int v : g[u]) {\n if (!sv.composite[v])\n continue;\n long long k = dsu.size[dsu.find(v)];\n cur += k; // pairs of nodes in the current component to the prime itself\n }\n ans += cur;\n }\n return ans;\n }\n};\n```
1
0
['Union Find', 'Number Theory', 'C++']
0
count-valid-paths-in-a-tree
Lobster? Count "cliques" & "Sum of pair-wise products"
lobster-count-cliques-sum-of-pair-wise-p-fvu4
Intuition\n"Lobster Graph" may be visually similar although not exactly identical.\n\n# Approach\n1) BFS and find how many non-prime nodes can be reached. Get a
quadpixels
NORMAL
2023-09-24T04:04:59.004295+00:00
2023-09-24T04:04:59.004323+00:00
107
false
# Intuition\n"Lobster Graph" may be visually similar although not exactly identical.\n\n# Approach\n1) BFS and find how many non-prime nodes can be reached. Get a list of # of reachable nodes.\n * Note: cache the results along the way\n2) Apply an algorithm to compute the sum of pairwise products: ((Sum of elements)^2 - (Sum of element\'s squares)/2\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n static bitset<100011> primez;\n static bool inited;\n vector<vector<int>> neighs;\n \n unordered_map<long long, int> dp;\n long long ToKey(int a, int b) {\n return a*100001LL+b;\n }\n \n int BfsCountVisited(int prime, int start, bitset<111111> visited) {\n if (primez.test(start)) return 0;\n long long key = ToKey(prime, start);\n if (dp.count(key) > 0) {\n //printf("Hit (%d,%d)\\n", prime, start);\n return dp.at(key);\n }\n\n int ret = 0;\n int cnt = visited.count();\n vector<int> n2v;\n n2v.push_back(start);\n vector<long long> encounters;\n encounters.push_back(ToKey(prime, start));\n \n while (!n2v.empty()) {\n vector<int> n2v_next;\n for (int x : n2v) { visited.set(x); }\n for (int x : n2v) {\n for (int n : neighs[x]) {\n if (primez.test(n) == true) {\n encounters.push_back(ToKey(n, x));\n }\n if (visited.test(n) == false &&\n primez.test(n) == false) {\n n2v_next.push_back(n);\n }\n }\n }\n n2v = n2v_next;\n }\n \n ret = visited.count() - cnt;\n for (const auto& enc : encounters) {\n dp[enc] = ret;\n }\n return ret;\n }\n \n long long SumOfLobster(vector<int>& x) {\n long long sum=0, sum_sq = 0;\n for (long long e : x) {\n sum += e;\n sum_sq += e*e;\n }\n return (sum*sum - sum_sq)/2 + sum;\n }\n \n long long countPaths(int n, vector<vector<int>>& edges) {\n neighs.resize(n+1);\n \n if (!inited) {\n primez.set();\n primez.reset(1);\n for (int i=2; i<100011; i++) {\n if (primez.test(i) == false) continue;\n for (int x=i*2; x<100011; x+=i) {\n primez.reset(x);\n }\n }\n /*\n for (int i=1; i<100011; i++) {\n if (primez.test(i)) printf("%d ", i);\n }\n printf("\\n");*/\n inited = true;\n }\n \n for (const auto& e : edges) {\n int n0 = e[0], n1 = e[1];\n neighs[n0].push_back(n1);\n neighs[n1].push_back(n0);\n }\n \n long long ret = 0;\n for (int i=1; i<=n; i++) {\n if (primez.test(i)== false) continue;\n vector<int> lobster;\n bitset<111111> visited;\n visited.set(i);\n for (int n : neighs[i]) {\n int haha = BfsCountVisited(i, n, visited);\n // printf("%d->%d haha=%d\\n", i, n, haha);\n lobster.push_back(haha);\n }\n \n long long lobster_sum = SumOfLobster(lobster);\n ret += lobster_sum;\n }\n return ret;\n }\n};\nbool Solution::inited = false;\nbitset<100011> Solution::primez;\n```
1
0
['C++']
0
count-valid-paths-in-a-tree
Union Find || C++
union-find-c-by-jakevk-79h4
Group composite nodes together using union find.\n\nThen iterate over primes and use math to count paths going through prime nodes.\n\n\nclass Solution {\npubli
jakevk
NORMAL
2023-09-24T04:01:27.935015+00:00
2023-09-24T04:05:48.626892+00:00
254
false
Group composite nodes together using union find.\n\nThen iterate over primes and use math to count paths going through prime nodes.\n\n```\nclass Solution {\npublic:\n #define ll long long\n #define N 100001\n \n int p[N], sz[N], is_prime[N];\n \n // dsu helper functions (template)\n int find(int v) {\n if (p[v] == v) return v;\n return p[v] = find(p[v]);\n }\n void join(int a, int b) {\n a = find(a), b = find(b);\n if (a == b) return;\n\n if (sz[a] < sz[b]) swap(a, b);\n p[b] = a;\n sz[a] += sz[b];\n }\n \n long long countPaths(int n, vector<vector<int>>& edges) {\n // generate primes\n fill(is_prime + 2, is_prime + n + 1, 1);\n vector<int> primes;\n for (ll i = 2; i <= n; ++i) {\n if (is_prime[i]) {\n primes.push_back(i);\n for (ll j = i * i; j <= n; j += i) {\n is_prime[j] = 0;\n }\n }\n }\n \n // graph setup\n vector<vector<int>> g(n);\n for (vector<int>& e: edges) {\n g[e[0]-1].push_back(e[1]-1);\n g[e[1]-1].push_back(e[0]-1);\n }\n \n // dsu setup\n iota(p, p + n, 0);\n fill(sz, sz + n, 1);\n for (vector<int>& e: edges)\n if (!is_prime[e[0]] && !is_prime[e[1]])\n join(e[0] - 1, e[1] - 1);\n \n // use math to count the number of paths for each prime\n ll ans = 0;\n for (int prime: primes) {\n vector<ll> group_sizes;\n ll end_at_prime = 0, pass_through_prime = 0;\n \n for (int nb: g[prime-1]) {\n if (is_prime[nb+1]) continue;\n ll group_size = sz[find(nb)];\n group_sizes.push_back(group_size);\n end_at_prime += group_size;\n }\n \n for (ll group_size: group_sizes)\n pass_through_prime += group_size * (end_at_prime - group_size);\n pass_through_prime /= 2; // we counted each path twice (once from each end)\n \n ans += end_at_prime + pass_through_prime;\n }\n\n return ans;\n }\n};\n```
1
0
['C++']
0
count-valid-paths-in-a-tree
Python Hard
python-hard-by-lucasschnee-dn5w
null
lucasschnee
NORMAL
2025-02-11T02:08:51.393334+00:00
2025-02-11T02:08:51.393334+00:00
3
false
```python3 [] class UnionFind: def __init__(self, N): self.count = N self.parent = [i for i in range(N)] self.rank = [1] * N def find(self, p): if p != self.parent[p]: self.parent[p] = self.find(self.parent[p]) return self.parent[p] def union(self, p, q): prt, qrt = self.find(p), self.find(q) if prt == qrt: return False if self.rank[prt] >= self.rank[qrt]: self.parent[qrt] = prt self.rank[prt] += self.rank[qrt] else: self.parent[prt] = qrt self.rank[qrt] += self.rank[prt] self.count -= 1 return True class Solution: def countPaths(self, N: int, edges: List[List[int]]) -> int: N += 1 prime = [True] * N prime[0] = prime[1] = False for i in range(2, N): if prime[i]: x = i + i while x < N: prime[x] = False x += i UF = UnionFind(N) lookup = defaultdict(list) for u, v in edges: lookup[u].append(v) lookup[v].append(u) def dfs(u, prev): for v in lookup[u]: if v == prev: continue dfs(v, u) if not prime[u] and not prime[v]: UF.union(u, v) dfs(1, -1) total = 0 def dfs2(u, prev): nonlocal total A = [] for v in lookup[u]: if v == prev: continue dfs2(v, u) if prime[u] and not prime[v]: A.append(UF.rank[UF.find(v)]) if prev != -1 and prime[u] and not prime[prev]: A.append(UF.rank[UF.find(prev)]) s = 1 for x in A: total += s * x s += x dfs2(1, -1) return total ```
0
0
['Python3']
0
count-valid-paths-in-a-tree
◈ Python ◈ Tree ◈ DP
python-tree-dp-by-zurcalled_suruat-x8n8
Glossary of Terms and SymbolsP(x): A boolean function indicating if node x is prime. C(x): The set of children of node x. VP0​(x): The number of valid paths en
zurcalled_suruat
NORMAL
2025-01-14T18:10:29.675452+00:00
2025-01-14T18:15:02.154779+00:00
8
false
#### Glossary of Terms and Symbols $P(x)$: A boolean function indicating if node $x$ is prime. $C(x)$: The set of children of node $x$. $VP_0(x)$: The number of valid paths ending at $x$ with 0 prime nodes. $VP_1(x)$: The number of valid paths ending at $x$ with 1 prime node. $IP(x)$: The number of valid internal paths passing through $x$. $G_0$: The set of $$VP_0 $$values for all children of a node. $G_1$: The set of $$VP_1$$ values for all children of a node. ##### Visual and Mathematical Intuition Imagine a tree where some nodes are marked as "prime". We want to count the valid paths in this tree, where a valid path has at most one prime node. To count internal paths ($IP(x)$) passing through a node $x$, we combine paths from different children, ensuring at most one prime node per path. ##### Mathematical Formulation * Base Case (Leaf Node): - $VP_0(x) = 1 - P(x)$ - $VP_1(x) = P(x)$ - $IP(x) = 0$ * Recursive Case (Internal Node): - $VP_0(x) = 1 - P(x) + \sum_{c \in C(x)} VP_0(c)$ - $VP_1(x) = P(x) + \sum_{c \in C(x)} (VP_0(c) \text{ if } P(x) \text{ else } VP_1(c))$ - Optimized $IP(x)$: - Let $G_0 = \{VP_0(c) | c \in C(x)\}$ and $G_1 = \{VP_1(c) | c \in C(x)\}$ - $IP(x) = \begin{cases} \frac{1}{2} \left[ \left( \sum_{g_0 \in G_0} g_0 \right) \cdot \left( \sum_{g_1 \in G_1} g_1 \right) - \sum_{c \in C(x)} (VP_0(c) \cdot VP_1(c)) \right] & \text{if } P(x) \\ \left( \sum_{g_0 \in G_0} g_0 \right) \cdot \left( \sum_{g_1 \in G_1} g_1 \right) - \sum_{c \in C(x)} (VP_0(c) \cdot VP_1(c)) & \text{if } \neg P(x) \end{cases}$ * Total Valid Paths: - $Total\_VP = \sum_{x} (VP(x) + IP(x))$ ##### Derivation of Optimized IP(x) Calculation and Adjustment for Prime Parent 1. Start with the original IP(x) recurrence: $IP(x) = \sum_{c_1, c_2 \in C(x), c_1 \neq c_2} (VP_1(c_1) \cdot VP_0(c_2) + VP_0(c_1) \cdot VP_1(c_2))$ 2. Expand the summation and rearrange terms: Let's represent the sets of $VP_0$ and $VP_1$ values of the children of $x$ as $G_0$ and $G_1$ respectively: $G_0 = \{VP_0(c) | c \in C(x)\}$ $G_1 = \{VP_1(c) | c \in C(x)\}$ Now, expanding the summation and rearranging, we get: $IP(x) = \sum_{g_0 \in G_0} \sum_{\substack{g_1 \in G_1 \\ g_0 \text{ and } g_1 \text{ from different children}}} (g_0 \cdot g_1)$ 3. Express as product of sums minus invalid terms: This can be expressed as the product of the sums of the two groups minus the sum of the products of corresponding elements: $IP(x) = \left( \sum_{g_0 \in G_0} g_0 \right) \cdot \left( \sum_{g_1 \in G_1} g_1 \right) - \sum_{c \in C(x)} (VP_0(c) \cdot VP_1(c))$ 4. Adjustment for Prime and Non-Prime Parent: * **Case 1: Parent node (x) is prime ($P(x)$)** In this case, we need to divide the $IP(x)$ by 2 to avoid overcounting. This is because swapping the order of children $c_1$ and $c_2$ in the original summation results in the same internal path when the parent is prime. For example, if $c_1$ has a path with 0 primes and $c_2$ has a path with 1 prime, it's the same path as when $c_1$ has a path with 1 prime and $c_2$ has a path with 0 primes, as the parent node contributes the only prime node to the path. Therefore, the optimized $IP(x)$ calculation with the adjustment is: $IP(x) = \frac{1}{2} \left[ \left( \sum_{g_0 \in G_0} g_0 \right) \cdot \left( \sum_{g_1 \in G_1} g_1 \right) - \sum_{c \in C(x)} (VP_0(c) \cdot VP_1(c)) \right]$ * **Case 2: Parent node (x) is not prime ($\neg P(x)$)** In this case, we don't need to divide by 2. Swapping the order of children $c_1$ and $c_2$ results in different internal paths, as the paths have distinct starting and ending points within the subtrees. Therefore, the optimized $IP(x)$ calculation is: $IP(x) = \left( \sum_{g_0 \in G_0} g_0 \right) \cdot \left( \sum_{g_1 \in G_1} g_1 \right) - \sum_{c \in C(x)} (VP_0(c) \cdot VP_1(c))$ This derivation shows how the original $O(n^2)$ complexity is reduced to $O(n)$ by using the product of sums and incorporating the adjustment for prime parents. ##### Mathematical Proof of Correctness The proof relies on the correct implementation of the recurrence relations and the bottom-up BFS traversal. 1. _Base Case_: The initialization of `prime0` and `prime1` for leaf nodes correctly establishes the base cases. 2. _Inductive Step_: The BFS traversal ensures that the counts for a node are computed only after its children's counts are finalized. The optimized calculation of `prime1_internal` correctly accumulates internal paths by considering combinations of paths from different children, while ensuring the validity condition (at most one prime node). 3. _Total Count_: Summing up the `prime1` and `prime1_internal` values for all nodes, with adjustments for prime nodes, gives the correct total count of valid paths. ##### Edge Cases and Confusing Parts * _Empty Children_: If a node has no children, the `groups` lists will be empty, and the sums will be 0. The calculation will still be correct, resulting in `prime1_internal = 0`. * _Prime Parent Adjustment_: The division by 2 when the parent is prime is crucial to avoid overcounting. This might seem counterintuitive at first, but it's necessary to ensure the correctness of the count. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] from collections import defaultdict as dd, deque as dq from itertools import combinations as combs from functools import lru_cache class T1: def __init__(self, val = None,prime0 = 0 , prime1 = 0 ): """ Visual Intuition of this Class: Consider we choos any node as the tree root. Now, we can define uniquely what the subtree rooted at a given node means with the perspective given by the overall root of the whole tree. This class now represents some information about the sub tree rooted at a given node:- (i) prime0 - is the count of paths ( >0 edges) starting at current node and ending at leaf with 0 prime node (ii) prime1 - is the count of paths ( >0 edges) starting at current node and ending at leaf with 1 prime node (iii) prime1_internal - is the count of paths ( >0 edges) starting one child subtree passing throught current node and then going to another child subtree with the condition of having 1 prime node """ self.val = val self.prime0 = prime0 self.prime1 = prime1 self.prime1_internal = 0 def __repr__(self): return "T1(v-{},0p-{},1p-{},1p-intrnl-{})".format( self.val, self.prime0, self.prime1, self.prime1_internal ) class Util1: def __init__(self, edges = []): self.nbrs = dd(lambda : dd(lambda : False)) self.compute_nbrs(edges) def compute_nbrs(self, edges): nbrs = dd(lambda : dd(lambda : False)) for nd1, nd2 in edges: nbrs[nd1][nd2] = True nbrs[nd2][nd1] = True self.nbrs = nbrs return nbrs def delete_node(self, nd): nbrs = self.nbrs if(nd not in nbrs): return for nd1 in nbrs[nd]: del nbrs[nd1][nd] if(len(nbrs[nd1].keys()) == 0): del nbrs[nd1] del nbrs[nd] class Solution: def countPaths(self, N: int, edges: List[List[int]]) -> int: nodes = set() leaf_nodes = set() treeUtil = Util1(edges) def compute_primes(N): primes = [] for i in range(2, N +1): is_prime = all( i % j != 0 for j in primes if j * j <= i ) if(is_prime): primes.append(i) return primes is_prime = dd(lambda : False) for p in compute_primes(N): is_prime[p] = True @lru_cache(maxsize=None) def ip(n): nonlocal is_prime, N assert 1<=n<=N return is_prime[n] node_info = dd(T1) for nd in range(1, N+1): node_info[nd].prime0 = (1 if(not ip(nd) )else 0) node_info[nd].prime1 = (1 if(ip(nd))else 0) if(len(edges)==0): return 0 # choose any node as the root node root_nd = edges[0][0] parent = dd(lambda : None) children = dd(lambda : set()) # bfs from root_nd wave = set([root_nd]) nds_by_depth = dd(lambda : set()) n_waves = 1 while(True): if(len(wave) == 0): break # print("wave=",wave) for nd in wave: nds_by_depth[n_waves].add(nd) node_info[nd].val = nd wave1 = set() for nd in wave: if(nd not in treeUtil.nbrs): continue for nd1 in treeUtil.nbrs[nd]: parent[nd1] = nd children[nd].add(nd1) wave1.add(nd1) for nd in wave: treeUtil.delete_node(nd) wave = wave1 n_waves += 1 # print("===parents", parent.items()) for depth in reversed(range(1 , n_waves)): parent_nds = set() if(depth-1 not in nds_by_depth)else nds_by_depth[depth-1] for parent_nd in parent_nds: if(parent_nd is None): continue node_info[parent_nd].val = parent_nd children_nds= list(children[parent_nd]) is_parent_nd_prime = ip(parent_nd) if(parent_nd in [1,2]): pass for nd in children_nds: is_nd_prime = ip(nd) if(is_parent_nd_prime): node_info[parent_nd].prime1 += ( node_info[nd].prime0 ) node_info[parent_nd].prime0 += 0 else: node_info[parent_nd].prime1 += ( node_info[nd].prime1 ) node_info[parent_nd].prime0 += ( node_info[nd].prime0 ) groups = [[],[]] if(is_parent_nd_prime): """ group = prent_nd->child_i->0primes for child_i of parent_nd """ group0 = [node_info[nd].prime0 for nd in children_nds] groups = [group0,group0] pass else: """ group0 = prent_nd->child_i->0primes for child_i of parent_nd group1 = prent_nd->child_i->1primes for child_i of parent_nd sum(group0) * sum(group1) """ group0 = [node_info[nd].prime0 for nd in children_nds] group1 = [node_info[nd].prime1 for nd in children_nds] groups = [group0,group1] assert len(groups[0]) == len(groups[1]) == len(children_nds) """ assert len(group0) == len(group1) == len([parent_nd->child for child in children[prent_nd]) Number of internal pats from one child to another child:- =g0_i x g1_j s.t. i != j =sum(group0) sum(group1) - sum( g0_i ^ g1_i for i in len(group0)) """ groups_prod_of_sum = ( sum(groups[0]) * sum(groups[1]) ) groups_prod_invalid_terms = sum([ ( groups[0][i] * groups[1][i] ) for i in range(len(children_nds)) ]) node_info[parent_nd].prime1_internal = ( groups_prod_of_sum - groups_prod_invalid_terms ) if(is_parent_nd_prime): node_info[parent_nd].prime1_internal = node_info[parent_nd].prime1_internal // 2 res = 0 for nd in range(1,N+1): if(nd in node_info ): res += ( node_info[nd].prime1 + node_info[nd].prime1_internal - (0 if(not ip(nd))else 1) ) # print(node_info[nd]) return res ```
0
0
['Dynamic Programming', 'Tree', 'Python3']
0
count-valid-paths-in-a-tree
Easy C++ solution using DSU.
easy-c-solution-using-dsu-by-aadikashyap-h2cg
IntuitionApproachmerge all the non-prime nodes for a subtree into a component and using these non-prime nodes we can make a path to the prime nodes.Complexity T
spidycoder178
NORMAL
2024-12-20T12:37:06.124414+00:00
2024-12-20T12:37:06.124414+00:00
9
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> merge all the non-prime nodes for a subtree into a component and using these non-prime nodes we can make a path to the prime nodes. # Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] const int N = 2e5+8; #define ll long long class DSU{ public: vector<ll> parent,rank; DSU(ll n){ parent.resize(n+1); for(ll i=1;i<=n;i++)parent[i]=i; rank.resize(n+1,1); } ll findParent(ll node){ if(node!=parent[node]){ return findParent(parent[node]); } return parent[node]; } void unite(ll u,ll v){ ll x=findParent(u); ll y=findParent(v); if(x!=y){ if(rank[x]>rank[y]){ parent[y]=x; rank[x]+=rank[y]; }else{ parent[x]=y; rank[y]+=rank[x]; } } } }; class Solution { public: vector<bool> seive() { vector<bool> primes(N, true); primes[0] = primes[1] = false; for (ll i = 2; i * i < N; i++) { if (primes[i]) { for (long long j = i * i; j < N; j += i) { primes[j] = false; } } } return primes; } long long countPaths(int n, vector<vector<int>>& edges) { vector<bool> prime = seive(); vector<vector<ll>> adj(n+1); DSU ds(n); for(auto it:edges){ ll u = it[0]; ll v = it[1]; adj[u].push_back(v); adj[v].push_back(u); if(prime[u] or prime[v])continue; //if nodes are not prime then merge them using DSU. ds.unite(u,v); } ll ans=0; for(ll i=1;i<=n;i++){ //if current node is prime we will find the size of subtree of non-prime nodes in the child of current node. if(prime[i]){ vector<ll> nodes; long long sum = 0; for (auto e: adj[i]) { //if any node is prime then skip it. if (prime[e]) continue; //else find the size of non-prime nodes. nodes.push_back(ds.rank[ds.findParent(e)]); //taking the sum of all non-prime nodes size. sum += nodes.back(); } ll curr=0; for (auto i : nodes) { //making all distinct paths using current size of non-prime nodes by remving the contribution of curr from sum i.e (sum-curr) and then multiplying the size of current subtree. curr += (sum-i)*i; } //as each path is counted twice so divide it by 2. curr/=2; //adding the sum into path as path from each on non-prime nodes can made to the prime node i. curr+=sum; //adding to the answer. ans+=curr; } } return ans; } }; ```
0
0
['Math', 'Dynamic Programming', 'Tree', 'Depth-First Search', 'Union Find', 'Number Theory', 'C++']
0
count-valid-paths-in-a-tree
C++ Solution
c-solution-by-jeffrey288-yamf
Approach\n- think of the number of paths passing through each prime number node p\n - the path must pass through two distinct edges incident to p\n - if y
Jeffrey288
NORMAL
2024-10-17T14:27:08.764911+00:00
2024-10-17T14:27:08.764944+00:00
6
false
# Approach\n- think of the number of paths passing through each prime number node `p`\n - the path must pass through two distinct edges incident to `p`\n - if you remove the prime number nodes, you can segment the whole tree into multiple connected components\n - the start and end nodes must come from **two distinct connected components** that are led to by each of those two incident edges\n- also remember that `p` can be one of the starting nodes\n\n- algorithm:\n - dfs/bfs to find size of all connected components\n - for each prime number node `p`, find the size of the connected components next to it\n - no. of paths = sum of product of pairwise connected components (paths from one cc to another) + sum of sizes of all connected components (paths where `p` is one of the starting nodes)\n\n# Complexity\n- Time complexity: O(Nsqrt(N)) (prime number seive) + O(NlogN) (bfs) + O(N) (calculating the no. of paths)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N^2) (storing adj graph)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<vector<int>> adj(n + 1);\n vector<int> cc(n + 1, -1);\n unordered_map<int, int> cc_size;\n\n vector<bool> is_prime(n + 1, true);\n is_prime[1] = false;\n for (long long i = 2; i <= n; i++) {\n for (long long j = 2; j * j <= i; j++) {\n if (i % j == 0) {\n is_prime[i] = false;\n break;\n }\n }\n if (is_prime[i]) {\n cc[i] = -2;\n }\n }\n\n for (auto edge: edges) {\n adj[edge[0]].emplace_back(edge[1]);\n adj[edge[1]].emplace_back(edge[0]);\n }\n\n // find connected components\n queue<int> q; // bfs \n for (int i = 1; i <= n; i++) {\n if (cc[i] == -1) { // haven\'t visited\n int sz = 1;\n cc[i] = i;\n q.push(i);\n while (!q.empty()) {\n int cur = q.front();\n q.pop();\n for (int neigh: adj[cur]) {\n if (cc[neigh] == -1) { // haven\'t visited\n cc[neigh] = i;\n sz++;\n q.push(neigh);\n }\n }\n }\n cc_size[i] = sz;\n }\n }\n\n // for each prime number, find paths passing through it\n long long num_paths = 0;\n for (int p = 1; p <= n; p++) {\n if (is_prime[p]) {\n long long sum_single = 0; \n long long sum_pairs = 0;\n for (int neigh: adj[p]) {\n if (!is_prime[neigh]) {\n int sz = cc_size[cc[neigh]];\n sum_pairs += sz * sum_single;\n sum_single += sz;\n }\n }\n num_paths += sum_single + sum_pairs;\n }\n }\n\n return num_paths;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
Elegant DSU merge composite subgraphs
elegant-dsu-merge-composite-subgraphs-by-nxhi
\nMAX = 1 + 10 ** 5\n\nv = [False] * MAX\nsp = [0] * MAX\n\nfor i in range(2, MAX, 2):\n sp[i] = 2\n\nfor i in range(3, MAX, 2):\n if not v[i]:\n s
theabbie
NORMAL
2024-10-15T03:08:54.521250+00:00
2024-10-15T03:08:54.521271+00:00
1
false
```\nMAX = 1 + 10 ** 5\n\nv = [False] * MAX\nsp = [0] * MAX\n\nfor i in range(2, MAX, 2):\n sp[i] = 2\n\nfor i in range(3, MAX, 2):\n if not v[i]:\n sp[i] = i\n j = i\n while j * i < MAX:\n if not v[j * i]:\n v[j * i] = True\n sp[j * i] = i\n j += 2\n \nclass DSU:\n def __init__(self, n):\n self.parent = list(range(n))\n self.size = [1] * n\n \n def find(self, a):\n if a == self.parent[a]:\n return a\n self.parent[a] = self.find(self.parent[a])\n return self.parent[a]\n \n def union(self, a, b):\n parent_a = self.find(a)\n parent_b = self.find(b)\n if parent_a != parent_b:\n if self.size[parent_a] < self.size[parent_b]:\n parent_a, parent_b = parent_b, parent_a\n self.parent[parent_b] = parent_a\n self.size[parent_a] += self.size[parent_b]\n\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = [[] for _ in range(n + 1)]\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n dsu = DSU(n + 1)\n for u, v in edges:\n if sp[u] != u and sp[v] != v:\n dsu.union(u, v)\n res = 0\n for i in range(1, n + 1):\n if sp[i] != i:\n continue\n ctr = 0\n for j in graph[i]:\n if sp[j] != j:\n res += dsu.size[dsu.find(j)] * (ctr + 1)\n ctr += dsu.size[dsu.find(j)]\n return res\n```
0
0
['Python']
0
count-valid-paths-in-a-tree
DFS/DP + Sieve of Eratosthenes O(n) clean C++ code with comments
dfsdp-sieve-of-eratosthenes-on-clean-c-c-5p51
Intuition\nAt each node, we need to compute 2 sums -\n\n1. dp[0][u]: number of vertical paths starting at u that contain no prime number (0 primes => index 0 fo
user9276g
NORMAL
2024-10-09T16:51:53.343893+00:00
2024-10-09T16:58:31.212299+00:00
4
false
# Intuition\nAt each node, we need to compute 2 sums -\n\n1. `dp[0][u]`: number of vertical paths starting at `u` that contain no prime number (0 primes => index 0 for convention)\n2. `dp[1][u]`: number of vertical paths starting at `u` that contain exactly 1 prime number (1 prime => index 1 for convention)\n\nThese sums can be computed using DFS traversal (details in Approach below). Once computed, then for each node `u`, we compute total number of paths containing exactly 1 prime and containing `u`. These paths can be of 2 types -\n1. prime paths starting at `u`: `dp[1][u]` but with a little nuance (see Approach).\n2. cross paths at `u`: number of paths (a, b) where $$a \\in subtree(child[i])$$ and $$b \\in subtree(child[j])$$, for each pair of (i, j) of children of `u`.\n\nThe final answer is then sum of paths at each node, which can be computed in DFS manner.\n\n# Approach\n## Step 1 - Compute prime[n+1] array\nFor $$10^5$$ numbers, we can compute `prime[n+1]` array using Sieve of Eratosthenes algorithm. It is a well known algorithm that computes it in $$O(n \\log \\log n)$$ and is left for the reader to Google for brevity. Note that `prime[1] = 0` and start from `1..n` instead of `0` as node labels are such.\n\n## Step 2 - Compute dp[2][n+1] sums using DFS\nWe define 2 sums as follows -\n- `dp[0][u]`: paths starting at `u` that contain 0 primes\n- `dp[1][u]`: paths starting at `u` that contain 1 prime\n\nThen consider a DFS traversal at node `u`. There are 2 cases now -\n1. `u` is prime: In this case, just `{u}` can be thought of as a single node prime path starting and ending at `u`. So, we can compute the sums as -\n - `dp[0][u]` = 0, since no path can be made ending at `u` that contain 0 primes since `u` itself is prime.\n - `dp[1][u]` = $$(\\sum dp[0][v]) + 1$$ for `v` child of `u`. Since `u` is already prime and we don\'t want 2 primes in a path, we just count non-prime paths for all children and append `u` in it. We also add just `{u}` as a 1-node path in this count (+1 for this reason).\n2. `u` is non-prime: Now `u` is a normal node, so - \n - `dp[0][u]` = $$\\sum dp[0][v]$$, i.e. append `u` to all non-prime paths in ending at all children.\n - `dp[1][u]` = $$\\sum dp[1][v]$$, i.e. append `u` to all prime paths ending at all children.\n\n## Step 3 - Compute paths at each node\nA path containing exactly 1 prime can be of 2 types - \n1. Vertical path: Path starts at node `u` and goes down in one of it\'s child subtrees entirely.\n - if `u` is prime: this is then `dp[1][u] - 1`. We subtract 1 to remove single node path `{u}` from this count as `u` is prime.\n - if `u` is non-prime: this is then `dp[1][u]` and we don\'t need any subtraction since `u` isn\'t prime and isn\'t counted.\n2. Cross path: Path starts at a node $$a \\in subtree(i)$$ and ends at node $$b \\in subtree(j)$$ for some child node i, j of `u`. Consider following cases -\n - if `u` is prime: In this case, `a` and `b` must be non-prime nodes and path looks like $$(a\\xrightarrow {non-prime\\ path} u\\xrightarrow {non-prime\\ path} b)$$. \n - Now `dp[1][u] - 1` is sum of all non-prime paths under `u` because `u` is the only prime in all prime paths and we count all those and remove 1-node `{u}` path to get all non-prime paths. \n - So `dp[1][u] - 1 - dp[0][v]` is sum of all non-prime paths under `u` except from child `v`. Hence, total cross paths become $$\\sum(dp[0][v]*(dp[1][u] - 1 - dp[0][v]))$$\n - Here we count paths (a, b) and (b, a) separately. Hence we must divide sum by 2 to get only unique paths.\n \n - if `u` is non-prime: In this case, one of `a` and `b` must be non-prime and other must be a prime node. Without loss of generalization, the path looks like $$(a\\xrightarrow {non-prime\\ path} u\\xrightarrow {prime\\ path} b)$$. \n - Now `dp[1][u] - dp[1][v]` is sum of all prime paths under `u` except those coming from subtree rooted at child `v`.\n - So now total cross paths that originate from `v` and end up in some other subtree of `u` become $$\\sum(dp[0][v]*(dp[1][u] - dp[1][v]))$$\n - Note that we do not have duplicate paths here because in path (a,b), (a,u) is non-prime path and (u,b) is a prime path. Hence we don\'t divide sum by 2.\n - There is also no "-1" since `u` isn\'t prime and is not counted in prime paths (u,b). \n\nAdding these 2 paths give us paths at a given node. Having computed these sums at a given node, we then recursively calculate them in all child nodes and aggregate using DFS.\n\n# Complexity\n- Time complexity:\n$$O(n)$$ because each node is visited only $$O(1)$$ time in each computation. (except prime computation which is $$O(n \\log \\log n)$$ )\n\n- Space complexity:\n$$O(n)$$ for dp[2][n+1], prime[n+1], adj[] graph\n\n# Code\n```cpp []\nclass Solution {\n vector<int> prime;\n // dp[0][u] = vertical paths starting from u containing 0 primes\n // dp[1][u] = vertical paths starting from u containing only 1 prime\n vector<long long> dp[2];\n vector<vector<int>> adj;\n\n void makePrime(int n) {\n prime.resize(n, 1);\n prime[1] = 0;\n for (int i = 2; i*i <= n; i++)\n if (prime[i])\n for (int j = i*i; j < n; j+=i)\n prime[j] = 0;\n }\n\n void dfs(int u, int p) {\n dp[0][u] = prime[u] ? 0 : 1;\n dp[1][u] = prime[u] ? 1 : 0;\n for (int v: adj[u]) {\n if (v != p) {\n dfs(v, u);\n\n // if u is prime, there can\'t be any path with 0 primes,\n // so just count when u is not prime\n if (!prime[u])\n dp[0][u] += dp[0][v];\n\n if (prime[u])\n // u is prime so only count paths with 0 primes\n dp[1][u] += dp[0][v];\n else\n // u isn\'t prime so count all paths with 1 prime\n dp[1][u] += dp[1][v];\n }\n }\n }\n\n long long paths(int u, int p) {\n long long sum = 0;\n if (prime[u]) {\n // if u is prime, take all paths starting from u with 0 primes\n // and compose crossing paths with each other\n for (int v: adj[u]) if (v != p)\n sum += dp[0][v] * (dp[1][u] - 1 - dp[0][v]);\n // -1 to remove path {u} from dp[1][u] because u is also prime\n sum /= 2; // remove duplicates (a,b) and (b,a)\n sum += dp[1][u] - 1; // re-add paths with prime ending at u (except just {u})\n }\n else {\n // if u isn\'t prime, take all paths starting from u with 1 primes \n // and compose crossing paths with all paths starting from u with 0 primes\n for (int v: adj[u]) if (v != p)\n sum += dp[0][v] * (dp[1][u] - dp[1][v]);\n // this time no -1 from dp[1][u] because u isn\'t prime and isn\'t counted in dp[1][u]\n // Also no duplicates this time because we are crossing (0 prime paths) x (1 prime paths) at each child, which is a unique path. so no sum/2\n sum += dp[1][u]; // add paths with prime ending at u (again {u} isn\'t counted in dp[1][u] so no need to -1)\n }\n\n for (int v: adj[u]) if (v != p)\n sum += paths(v, u);\n return sum;\n }\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n makePrime(n+1);\n dp[0].resize(n+1, -1);\n dp[1].resize(n+1, -1);\n adj.resize(n+1);\n for (auto& e: edges) {\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n dfs(1, -1);\n return paths(1, -1);\n }\n};\n```
0
0
['Dynamic Programming', 'Tree', 'Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
C++ | Simple Solution | Sieve | DFS
c-simple-solution-sieve-dfs-by-deepakcha-kg7e
\n\n# Code\ncpp []\nint MAX_N = 100001;\nvector<int> is_prime(MAX_N, true);\nclass Solution {\npublic:\n\n Solution(){\n // Generate Sieve\n if
deepakchaurasiya
NORMAL
2024-09-21T19:33:39.247317+00:00
2024-09-21T19:33:39.247339+00:00
3
false
\n\n# Code\n```cpp []\nint MAX_N = 100001;\nvector<int> is_prime(MAX_N, true);\nclass Solution {\npublic:\n\n Solution(){\n // Generate Sieve\n if(!is_prime[1]) return;\n is_prime[0] = is_prime[1] = 0;\n for(int i=2; i*i<MAX_N; i++){\n if(is_prime[i]){\n for(int j=i*i; j<MAX_N; j+=i){\n is_prime[j] = false;\n }\n }\n }\n }\n // Count no. of nodes in all connected paths that dont have prime number\n int dfsCount( int node, vector<bool> &visited, vector<vector<int>> &adj){\n if(is_prime[node]) return 0;\n visited[node] = 1;\n int count = 1;\n for(auto nbr: adj[node]){\n if(!visited[nbr]){\n count+=dfsCount(nbr, visited, adj);\n }\n }\n return count;\n }\n // Mark all nodes in connected path with the count of total nodes (obtained from dfsCount()) \n void dfsMark( int node, int &count, vector<int>& nodes_count, vector<vector<int>> &adj){\n if(is_prime[node] || nodes_count[node]!=-1) return ;\n nodes_count[node] = count;\n \n for(auto nbr: adj[node]){\n dfsMark(nbr, count, nodes_count, adj);\n }\n }\n \n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<vector<int>> adj(n+1);\n for(auto& e: edges){\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n vector<bool> visited(n+1);\n vector<int> nodes_count(n+1, -1);\n for(int i=1; i<=n; i++){\n if(!is_prime[i] && !visited[i]){\n int count = dfsCount(i, visited, adj);\n dfsMark(i, count, nodes_count, adj);\n }\n }\n long long ans = 0;\n for(int i=1; i<=n; i++){\n if(is_prime[i]){\n long long count = 0, pairs = 0;\n for(auto& nbr: adj[i]){\n if(nodes_count[nbr]>0){\n long long count2 = nodes_count[nbr];\n pairs+=(count+1)*count2;\n count+=count2;\n // pairs+=(count*count2);\n // count+=count2;\n // pairs+=count2;\n }\n }\n ans+=pairs;\n }\n }\n return ans;\n\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
DSU solution
dsu-solution-by-rahulkumar665550-m8z4
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
rahulkumar665550
NORMAL
2024-09-04T04:09:23.673666+00:00
2024-09-04T04:09:23.673694+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nstruct DSU {\n vector<int> par;\n vector<int> cnt;\n \n DSU (int n) {\n par.resize(n+1, 0);\n cnt.resize(n+1, 1);\n \n for (int j = 0; j <= n; j ++) par[j] = j;\n }\n \n int Leader (int x) {\n if (x == par[x]) return x;\n return (par[x] = Leader(par[x]));\n }\n \n void Merge (int x, int y) {\n x = Leader(x);\n y = Leader(y);\n \n if (x == y) return;\n if (cnt[x] > cnt[y]) swap(x, y);\n \n cnt[y] += cnt[x];\n par[x] = y;\n }\n};\n\nconst int N = 1e5 + 1;\nvector<vector<int>> g(N);\n\nvector<int> sieve(N, 0);\nbool sieve_build = false;\n\nclass Solution {\n\n void build_sieve(){\n if(sieve_build) return;\n\n sieve_build = true;\n\n for(int j=2; j<N; j++){\n if(!sieve[j]) sieve[j] = j;\n\n for(int k=j+j; k<N; k+=j)\n if(!sieve[k]) sieve[k] = j;\n }\n }\n\n bool is_prime(int x){\n return sieve[x] == x;\n }\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n build_sieve();\n for(int j=0; j<=n; j++) g[j].clear();\n\n DSU dsu(n);\n\n for(auto i : edges){\n int u = i[0], v = i[1];\n g[u].push_back(v);\n g[v].push_back(u);\n\n bool u_is_prime = is_prime(u); \n bool v_is_prime = is_prime(v); \n\n if(u_is_prime || v_is_prime) continue;\n dsu.Merge(u, v);\n }\n\n long long result = 0;\n\n for(int j=1; j<=n; j++){\n if(!is_prime(j)) continue;\n\n vector<int> nodes;\n long long sum = 1;\n\n for(auto e : g[j]){\n if(is_prime(e)) continue;\n\n nodes.push_back(dsu.cnt[dsu.Leader(e)]);\n sum += nodes.back();\n }\n\n for(auto i : nodes){\n sum -= i;\n result += sum * i;\n }\n }\n return result;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
DSU_________________________________________________________________AVS
dsu_____________________________________-lff7
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Vishal1431
NORMAL
2024-08-29T22:27:22.309295+00:00
2024-08-29T22:27:22.309323+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nconst int N = 1e5 + 5;\n\nclass Solution {\n vector<bool> isPrime;\n int par[N];\n int siz[N];\n\n void make(int v) {\n par[v] = v;\n siz[v] = 1;\n }\n\n int find(int v) {\n if (v == par[v]) return v;\n return par[v] = find(par[v]);\n }\n\n void Union(int a, int b) {\n a = find(a);\n b = find(b);\n if (a != b) {\n if (siz[a] < siz[b]) swap(a, b);\n par[b] = a;\n siz[a] += siz[b];\n }\n }\n\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n isPrime.assign(100006, true);\n isPrime[0] = false;\n isPrime[1] = false;\n for (int i = 2; i <= 100005; i++) {\n if (isPrime[i]) {\n for (int j = 2 * i; j <= 100005; j += i) {\n isPrime[j] = false;\n }\n }\n }\n\n for (int i = 1; i <= n; i++) {\n if (!isPrime[i]) make(i);\n }\n\n for (auto it : edges) {\n if (isPrime[it[0]] || isPrime[it[1]]) continue;\n Union(it[0], it[1]);\n }\n\n vector<vector<int>> g(n + 1);\n for (auto it : edges) {\n g[it[0]].push_back(it[1]);\n g[it[1]].push_back(it[0]);\n }\n\n long long ans = 0;\n\n for (int i = 1; i <= n; i++) {\n if (isPrime[i]) {\n vector<int> componentSizes;\n long long sum = 1;\n for (auto it : g[i]) {\n if (isPrime[it]) continue;\n componentSizes.push_back(siz[find(it)]);\n sum += componentSizes.back();\n }\n for (auto it : componentSizes) {\n sum -= it;\n ans += sum * it;\n }\n }\n }\n\n return ans;\n }\n};\n\n```
0
0
['Tree', 'Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
Simplest Solution with Easy Explanation ( using DSU)
simplest-solution-with-easy-explanation-nmt9f
Intuition\n Describe your first thoughts on how to solve this problem. \nWe have to calculate number of pair of vertices which have exactly one prime node in th
vikram_8009
NORMAL
2024-08-20T07:10:21.831943+00:00
2024-08-20T07:10:21.831974+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have to calculate number of pair of vertices which have exactly one prime node in their simple path. We can solve this problem by reconstructing the graph .\n# Approach\n<!-- Describe your approach to solving the problem. -->\n. We will make new graph.\n. We will add edges between only non-prime vertices.\n. Using DSU we will find the size of each component.\n. Traverse Through all prime vertices.\n. Now Calculate number of (a,b) which have this prime vertices in their simple path.\n. for calculation of this part \n. Each prime vertices have atmost 3 adjacent component.\n. total number of pair would be (sum of size of each non-prime component )+(sum of size of each two components).\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n $$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```cpp []\nclass Solution {\npublic:\n static const int N=1e5;\n\n bool prime[N+1];\n int sz[N+1];\n int par[N+1];\n void make_state(int n){\n for(int i=1;i<=n;i++){\n par[i]=i;\n sz[i]=1;\n }\n }\n\n int find(int v){\n if(par[v]==v)return v;\n return par[v]=find(par[v]);\n }\n\n void uni(int a, int b){\n a=find(a);\n b=find(b);\n if(a==b)return;\n if(sz[b]<sz[a])swap(a,b);\n par[a]=b;\n sz[b]+=sz[a];\n }\n\n void sieve(){\n prime[0]=prime[1]=true;\n for(int i=2;i<=N;i++){\n if(prime[i]==true)continue;\n for(int j=2*i;j<=N;j+=i){\n prime[j]=true;\n }\n }\n }\n\n\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<vector<int>>graph(n+1);\n fill(prime,prime+N,false);\n sieve();\n make_state(n);\n\n for(int i=1;i<=20;i++){\n if(!prime[i])cout<<i<<endl;\n }\n\n for(auto &edge:edges){\n graph[edge[0]].push_back(edge[1]);\n graph[edge[1]].push_back(edge[0]);\n if(prime[edge[0]] and prime[edge[1]]){\n uni(edge[0],edge[1]);\n }\n }\n\n for(int i=1;i<=n;i++){\n sz[i]=sz[find(i)];\n <!-- cout<<"sz["<<i<<"]"<<sz[i]<<endl; -->\n }\n long long res=0;\n for(int i=1;i<=n;i++){\n if(!prime[i]){\n vector<int>v;\n int sum =0;\n long long ans=0;\n for(auto &node : graph[i]){\n if(!prime[node])continue;\n v.push_back(sz[node]);\n sum+= sz[node];\n }\n\n for(auto &j:v){\n ans += (1LL*j*(sum-j));\n }\n ans/=2;\n res += (sum+ans);\n }\n }\n\n\n return res;\n }\n};\n```
0
0
['Union Find', 'Number Theory', 'C++']
0
count-valid-paths-in-a-tree
Rust: sieve & DFS
rust-sieve-dfs-by-minamikaze392-tqlg
Approach\n1. Find all prime numbers which are <= n with Sieve of Eratosthenes (O(n)).\n2. Pick a node and do recursive DFS. The recursive function returns three
Minamikaze392
NORMAL
2024-07-23T07:45:29.803193+00:00
2024-07-23T07:45:40.004355+00:00
3
false
# Approach\n1. Find all prime numbers which are `<= n` with Sieve of Eratosthenes ($$O(n)$$).\n2. Pick a node and do recursive DFS. The recursive function returns three values:\n- `ans`: Number of all **valid** paths in subtree.\n- `one`: Number of all paths which **ends** at the subtree **root**, and involves **one** prime node.\n- `zero`: Number of all paths which **ends** at the subtree **root**, and involves **zero** prime nodes.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nimpl Solution {\n pub fn count_paths(n: i32, edges: Vec<Vec<i32>>) -> i64 {\n let n = n as usize;\n let spf = Self::sieve(n);\n let mut adj = vec![Vec::<usize>::new(); n + 1];\n for (u, v) in edges.iter().map(|v| (v[0] as usize, v[1] as usize)) {\n adj[u].push(v);\n adj[v].push(u);\n }\n Self::tree_dfs(1, 1, &adj, &spf).0\n }\n\n fn sieve(n: usize) -> Vec<usize> {\n let mut spf: Vec<usize> = (0..=n).collect();\n spf[1] = 0;\n let mut primes = Vec::<usize>::new();\n for i in 2..=n {\n if spf[i] == i {\n primes.push(i);\n }\n for &p in primes.iter() {\n if p > spf[i] || p * i > n {\n break;\n }\n spf[p * i] = p;\n }\n }\n spf\n }\n\n fn tree_dfs(i: usize, prev: usize, adj: &Vec<Vec<usize>>, spf: &Vec<usize>) -> (i64, i64, i64) {\n let (mut ans, mut one, mut zero) = if spf[i] == i {\n (0, 1, 0)\n }\n else {\n (0, 0, 1)\n };\n for &j in adj[i].iter() {\n if j == prev {\n continue;\n }\n let (ans2, one2, zero2) = Self::tree_dfs(j, i, adj, spf);\n ans += ans2 + one * zero2 + zero * one2;\n if spf[i] == i {\n one += zero2;\n }\n else {\n one += one2;\n zero += zero2;\n }\n }\n (ans, one, zero)\n }\n}\n```
0
0
['Dynamic Programming', 'Depth-First Search', 'Rust']
0
count-valid-paths-in-a-tree
Simple DFS || No DP|| No DSU||O(N) Solution
simple-dfs-no-dp-no-dsuon-solution-by-sd-zbb2
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Sdas_1905
NORMAL
2024-07-04T19:45:14.043975+00:00
2024-07-04T19:45:14.044004+00:00
14
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(sqrt(n))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n #define ll long long \n bool is_prime(int n) {\n\n if (n <= 1)\n return false;\n if (n <= 3)\n return true;\n if (n % 2 == 0 || n % 3 == 0)\n return false;\n\n for (int i = 5; i <= std::sqrt(n); i += 6) {\n if (n % i == 0 || n % (i + 2) == 0) {\n return false;\n }\n }\n\n return true;\n }\n\n pair<ll, ll> dfs(vector<vector<int>>& adj, ll& primepath, int node,\n int parent) {\n pair<ll, ll> prime = {0, 0};\n ll nonprimecnt =0;\n ll primecnt =0;\n for (auto it : adj[node]) {\n if (it != parent) {\n pair<ll, ll> temp = dfs(adj, primepath, it, node);\n nonprimecnt+=(prime.first*temp.second +prime.second*temp.first);\n primecnt+=(prime.second*temp.second);\n prime.first += temp.first;\n prime.second += temp.second;\n }\n }\n if (is_prime(node)){\n primepath+= prime.second + primecnt;\n return {prime.second+1,0};\n }\n primepath+=prime.first+nonprimecnt;\n prime.second++;\n return prime;\n \n }\n\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<vector<int>> adj(n+1);\n for (auto it : edges) {\n adj[it[0]].push_back(it[1]);\n adj[it[1]].push_back(it[0]);\n }\n ll primepath =0;\n dfs(adj,primepath,1,-1);\n return primepath;\n }\n};\n```
0
0
['Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
Recursive solution | | easy to understand | | c++
recursive-solution-easy-to-understand-c-sdgp3
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
dl720125
NORMAL
2024-07-01T19:16:09.256148+00:00
2024-07-01T19:16:09.256167+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n const int N = 1e5+1;\n#define vvl vector<vector<int>> \nclass Solution {\npublic:\n bool prime[N + 1];\n \n void SieveOfEratosthenes() {\n memset(prime, true, sizeof(prime));\n for (int p = 2; p * p <= N; p++) {\n if (prime[p] == true) {\n for (int i = p * p; i <= N; i += p) prime[i] = false;\n }\n }\n prime[1]=false;\n }\n\n void dfs1(int nod, int p,vector<int> &indp,vector<int> &par,vvl &g){\n par[nod]=p;\n\n for(auto &ch:g[nod]){\n if(ch==p) continue;\n dfs1(ch,nod,indp,par,g);\n\n if(!prime[nod]) indp[nod] += indp[ch];\n }\n }\n void dfs2(int nod, int p, vector<int> &outdp,vector<int> &indp,vector<int> & par,vvl &g){\n if(!prime[nod]){\n if(!prime[par[nod]]) outdp[nod]=indp[p]-indp[nod] +outdp[p];\n }\n for(auto ch:g[nod]){\n if(ch==p) continue;\n \n dfs2(ch,nod,outdp,indp,par,g);\n\n }\n }\n long long f(vector<int> &v){\n int m=v.size();\n long long tot=0, ans=0;\n for(auto &i:v) tot+=i;\n long long sum=tot;\n\n for(int i=0;i<m;i++){\n tot-=v[i];\n ans+=(tot * v[i]);\n }\n return ans+sum;\n }\n long long countPaths(int n, vector<vector<int>>& e) {\n vector<vector<int>> g(n+1);\n\n for(int i=0;i<n-1;i++){\n g[e[i][0]].push_back(e[i][1]);\n g[e[i][1]].push_back(e[i][0]);\n }\n SieveOfEratosthenes();\n\n vector<int> indp(n+1,1), outdp(n+1),par(n+1);\n outdp[1]=0;\n for(int i=1;i<=n;i++){\n if(prime[i]){\n indp[i]=0; outdp[i]=0;\n }\n }\n dfs1(1,0,indp,par,g);\n dfs2(1,0,outdp,indp,par,g);\n\n long long ans=0;\n for(int i=1;i<=n;i++){\n if(prime[i]){\n vector<int> v;\n for(auto ch:g[i]){\n if(ch==par[i]) v.push_back(indp[ch]+outdp[ch]);\n else v.push_back(indp[ch]);\n }\n\n ans+= f(v);\n }\n }\n\n return ans;\n } \n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
C++ || DSU || Sieve
c-dsu-sieve-by-akash92-mwq2
\n# Approach\n Describe your approach to solving the problem. \nUse sieve to find prime numbers in range [1,n]. Then use dsu to first form union of all non prim
akash92
NORMAL
2024-06-01T05:15:58.295361+00:00
2024-06-01T05:15:58.295404+00:00
5
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse sieve to find prime numbers in range [1,n]. Then use dsu to first form union of all non prime nodes(node and adjNode are not prime), then form union where node is prime, adjNode is not prime.if(adjNode!=prime) find its ulp, and see if it is visited or not, if !visited then add size[adjNode]*nonPrimes to validPaths and increase nonPrimes+=size[adjNode] & vis[ulp]=true. After iterating over all the adjNodes of node, iterate once again on adjNodes of node to mark all the ulp unvisited.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass DisjointSet {\npublic:\n vector<int> parent, size;\n DisjointSet(int n) {\n parent.resize(n+1);\n size.resize(n+1);\n for(int i=0; i<=n; i++) {\n parent[i] = i;\n size[i] = 1;\n }\n }\n int findUPar(int node) {\n if(parent[node] == node) return node;\n return parent[node] = findUPar(parent[node]);\n }\n void unionBySize(int u, int v) {\n int ulpu = findUPar(u);\n int ulpv = findUPar(v);\n if(ulpu == ulpv) return;\n if(size[ulpu] < size[ulpv]) {\n parent[ulpu] = ulpv;\n size[ulpv] += size[ulpu];\n } else {\n parent[ulpv] = ulpu;\n size[ulpu] += size[ulpv];\n }\n }\n};\n\nclass Solution {\npublic:\n // Sieve\n vector<bool> getNPrimes(int n) {\n vector<bool> isPrime(n+1, true);\n isPrime[0] = isPrime[1] = false;\n for(int p = 2; p * p <= n; p++) {\n if(isPrime[p]) {\n for(int i = p * p; i <= n; i += p) {\n isPrime[i] = false;\n }\n }\n }\n return isPrime;\n }\n\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<bool> isPrime = getNPrimes(n);\n DisjointSet ds(n);\n\n vector<vector<int>> adj(n + 1);\n for(auto& edge : edges) {\n adj[edge[0]].push_back(edge[1]);\n adj[edge[1]].push_back(edge[0]);\n }\n\n // Union all non-prime nodes\n for(int node = 1; node <= n; node++) {\n if(!isPrime[node]) {\n for(int adjNode : adj[node]) {\n if(!isPrime[adjNode]) {\n ds.unionBySize(node, adjNode);\n }\n }\n }\n }\n\n // Count valid paths\n long long validPaths = 0;\n vector<bool> visited(n + 1, false);\n\n for(int node = 1; node <= n; node++) {\n if(isPrime[node]) {\n long long countNonPrimes = 1LL;\n for(int adjNode : adj[node]) {\n if(!isPrime[adjNode]) {\n int root = ds.findUPar(adjNode);\n if(!visited[root]) {\n validPaths += countNonPrimes * ds.size[root];\n countNonPrimes += ds.size[root];\n visited[root] = true;\n }\n }\n }\n for(int adjNode : adj[node]) {\n if(!isPrime[adjNode]) {\n int root = ds.findUPar(adjNode);\n visited[root] = false;\n }\n }\n }\n }\n\n return validPaths;\n }\n};\n\n```
0
0
['Union Find', 'C++']
0
count-valid-paths-in-a-tree
Easy Solution :)
easy-solution-by-user20222-miya
\n# Code\n\nvector<bool>pms(100005,1);\nauto a=[]()->int{\n pms[0]=0;\n pms[1]=0;\n for(int i=2;i<=1e5;i++){\n if(pms[i]){\n for(int
user20222
NORMAL
2024-05-18T18:38:17.729265+00:00
2024-05-18T18:38:17.729298+00:00
3
false
\n# Code\n```\nvector<bool>pms(100005,1);\nauto a=[]()->int{\n pms[0]=0;\n pms[1]=0;\n for(int i=2;i<=1e5;i++){\n if(pms[i]){\n for(int j=i+i;j<=1e5;j+=i){\n pms[j]=0;\n }\n }\n }\n return 0;\n}();\n\nclass Solution {\npublic:\n long long ans = 0;\n pair<int, int> f(vector<vector<int>>& graph, int node, int p) { \n vector<long long>rprime,nrprime;\n for (auto& ch : graph[node]) { // val.first = 4\n if (ch != p) {\n auto p = f(graph, ch, node); \n rprime.push_back(p.first); \n nrprime.push_back(p.second);\n }\n }\n pair<int,int>val={0,0};\n if(pms[node+1]){\n long long total = accumulate(rprime.begin(),rprime.end(),0LL);\n for(int i=0;i<rprime.size();i++){\n total = total-rprime[i];\n ans+=total*rprime[i];\n ans+=rprime[i];\n }\n val.second = accumulate(rprime.begin(),rprime.end(),1LL);\n }\n else{\n int totalrp = accumulate(rprime.begin(),rprime.end(),0LL);\n int totalnrp = accumulate(nrprime.begin(),nrprime.end(),0LL);\n for(int i=0;i<rprime.size();i++){\n totalrp = totalrp-rprime[i];\n totalnrp = totalnrp-nrprime[i];\n ans+=totalnrp*rprime[i];\n ans+=totalrp*nrprime[i];\n ans+=nrprime[i];\n }\n val.first = accumulate(rprime.begin(),rprime.end(),1LL);\n val.second = accumulate(nrprime.begin(),nrprime.end(),0LL);\n }\n return val;\n }\n long long countPaths(int n, vector<vector<int>>& edges) { \n vector<vector<int>> graph(n);\n for (auto& it : edges) {\n graph[it[0] - 1].push_back(it[1] - 1);\n graph[it[1] - 1].push_back(it[0] - 1);\n }\n f(graph, 0, -1);\n return ans;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
Dp + tree py3
dp-tree-py3-by-maxorgus-u6a7
This is really a hard one, I first tried dp by calculating number of paths without prime nodes starting from each prime node, but that gave me TLE in the last f
MaxOrgus
NORMAL
2024-04-25T04:39:14.688296+00:00
2024-04-25T04:39:14.688332+00:00
18
false
This is really a hard one, I first tried dp by calculating number of paths without prime nodes starting from each prime node, but that gave me TLE in the last few test cases.\n\nThen I followed the hint to restructure the tree so that edges be visited less, it barely passed. Also note that precomputing all prime numbers is much faster than checking whether a number is prime when needed\n\n# Code\n```\nMX = 100001\nlpf = [0] * MX\nfor i in range(2, MX):\n if lpf[i] == 0:\n for j in range(i, MX, i):\n lpf[j] = i\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {i:set([]) for i in range(1,n+1)}\n for u,v in edges:\n graph[u].add(v)\n graph[v].add(u)\n isprimes = [lpf[i] == i for i in range(1,n+1)]\n p = {i:-1 for i in range(1,n+1)}\n def reroot(node,pnode):\n p[node] = pnode\n for child in graph[node]:\n if child!=pnode:\n reroot(child,node)\n \n reroot(1,None)\n self.res = 0\n @cache \n def dp(node):\n with_p,without_p = 0,0\n if isprimes[node-1]:\n with_p = 1\n else:\n without_p = 1\n for child in graph[node]:\n if child!=p[node]:\n a,b = dp(child)\n if isprimes[node-1]:\n self.res += with_p*b\n with_p += b\n else:\n with_p += a\n without_p += b\n if not isprimes[node-1]:\n for child in graph[node]:\n if child!=p[node]:\n a,b = dp(child)\n self.res += a*(without_p - b)\n return with_p,without_p\n \n dp(1)\n return self.res\n\n \n \n```
0
0
['Dynamic Programming', 'Tree', 'Python3']
0
count-valid-paths-in-a-tree
My code shows exceed time limite for n=10000; anyone has any advice how to make it pass thank you
my-code-shows-exceed-time-limite-for-n10-x0bm
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
shirley716
NORMAL
2024-03-25T01:15:23.096019+00:00
2024-03-25T01:15:23.096048+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n ArrayList<Integer> primes ;\n int [] id;\n ArrayList<ArrayList<Integer>> next;;\n ArrayList<Long> nonPrime ;\n long primePathTotal = 0;\n\n public long countPaths(int n, int[][] edges) {\n primes = eratosthenes(n);\n id = new int [n+1];\n next=new ArrayList<>();\n nonPrime = new ArrayList<>();\n\n for(int i=0;i<=n;i++) {\n id[i] = i;\n next.add(new ArrayList<>());\n nonPrime.add(0L);\n }\n //initiate 0 to n value;\n //iterate edges and update parent info to id\n for(int i=0; i<edges.length;i++){\n int p=edges[i][0];\n int q=edges[i][1];\n //find all the nearby point for each of point\n next.get(p).add(q);\n next.get(q).add(p);\n // union\n if(!isPrime(p) && !isPrime(q))\n if(find(p)!=find(q))\n union(p,q);\n }\n\n //update the total of number to parent for all non-prime number\n\n int key;\n for(int i=1;i<=n;i++){\n key = id[i];\n nonPrime.set(key,nonPrime.get(key)+1);\n }\n for(int i=1;i<=n;i++){\n key = id[i];\n nonPrime.set(i,nonPrime.get(key));\n }\n\n //Iterate through all nearly by non prime point to see how may m1 for each of it;\n\n int prime,total=0,pathValue=0;\n ArrayList<Long> path;\n\n //iterate through the arrayList and id list\n for(int j=0; j<primes.size();j++){\n total=0;\n pathValue=0;\n prime=primes.get(j);\n path = new ArrayList<>();\n for(int nearestVal :next.get(prime))\n if(!isPrime(nearestVal)) {\n long value = nonPrime.get(nearestVal);\n path.add(value);\n total+= value;\n }\n\n\n for(int v = 0; v<path.size();v++)\n pathValue += (total-path.get(v))*path.get(v);\n\n primePathTotal+=pathValue/2+total;\n\n }\n return primePathTotal;\n }\n\n //find\n int find(int x){\n if(x!=id[x])\n id[x]=find(id[x]);\n return id[x];\n }\n //Union\n void union(int p,int q){\n int i = find(p);\n int j = find(q);\n if(i>j) id[i] = j;\n else id[j]=i;\n }\n\n //to see all prime numbers for num<=n;\n ArrayList<Integer> eratosthenes(int n)\n {\n // Create a boolean array "prime[0..n]" and\n // initialize all entries it as true. A value in\n // prime[i] will finally be false if i is Not a\n // prime, else true.\n boolean prime[] = new boolean[n + 1];\n ArrayList<Integer> arraylist = new ArrayList<>();\n for (int i = 0; i <= n; i++)\n prime[i] = true;\n\n for (int p = 2; p * p <= n; p++) {\n // If prime[p] is not changed, then it is a\n // prime\n if (prime[p] == true) {\n for (int i = p * p; i <= n; i += p)\n prime[i] = false;\n }\n }\n\n // Print all prime numbers\n for (int i = 2; i <= n; i++) {\n if (prime[i] == true)\n arraylist.add(i);\n }\n return arraylist;\n }\n // prime return boolean\n boolean isPrime(int x){\n return primes.contains(x);\n }\n\n //prime number\n}\n\n```
0
0
['Java']
0
count-valid-paths-in-a-tree
dfs
dfs-by-kebao-quan-hhdr
\nclass Solution {\n static constexpr uint32_t N = 100001;\n bool isPrime[100001];\n void dfs(vector<vector<int>> &G, vector<int> &seen, int i, int pre
kebao-quan
NORMAL
2024-03-15T22:22:01.227091+00:00
2024-03-15T22:22:01.227112+00:00
2
false
```\nclass Solution {\n static constexpr uint32_t N = 100001;\n bool isPrime[100001];\n void dfs(vector<vector<int>> &G, vector<int> &seen, int i, int pre) {\n seen.emplace_back(i);\n\n for (int j : G[i]) {\n if (isPrime[j] || j == pre) continue;\n dfs(G, seen, j, i);\n }\n }\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<vector<int>> G(n + 1);\n for (auto edge : edges) {\n G[edge[0]].emplace_back(edge[1]);\n G[edge[1]].emplace_back(edge[0]);\n }\n\n \n \n fill(&isPrime[0], &isPrime[0] + N, true);\n //Sieve of Eratosthenes\n isPrime[1] = false;\n for (uint32_t i = 2; i < N; i++) {\n if (isPrime[i]) {\n for (uint32_t j = i * i; j <= n; j+=i) {\n isPrime[j] = false;\n }\n }\n }\n\n vector<int> seen;\n vector<int> count(n + 1);\n uint32_t sum = 0;\n uint32_t cur = 0;\n long long res = 0;\n for (uint32_t i = 1; i <= n; i++) {\n if (!isPrime[i]) {\n continue;\n }\n\n sum = 0;\n cur = 0;\n for (int j : G[i]) {\n if (isPrime[j]) continue;\n if (count[j] == 0) {\n seen.clear();\n dfs(G, seen, j, i);\n for (int k = 0; k < seen.size(); k++) {\n count[seen[k]] = seen.size();\n }\n }\n sum += count[j] * cur;\n cur += count[j];\n }\n sum += cur;\n res += sum;\n }\n\n\n \n return res;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
Union Find and Counting
union-find-and-counting-by-trusty42-69dq
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
trusty42
NORMAL
2024-02-28T12:57:32.207141+00:00
2024-02-28T12:57:32.207169+00:00
13
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long countPaths(int n, int[][] edges) {\n Set<Integer> primes = getPrimes(n);\n int[] parents = new int[n+1];\n int[] uCounts = new int[n+1];\n\n Map<Integer, Integer> counts = new HashMap<Integer, Integer>();\n\n for(int i = 1; i <= n; i++) {\n parents[i] = i;\n uCounts[i] = 1;\n }\n // 0th element indicates number of connected nodes to this node, 1st, 2nd and 3rd elements are the connected nodes.\n Node[] graph = new Node[n+1];\n for(int i = 1; i <= n; i++) {\n graph[i] = new Node();\n }\n List<List<Integer>> connected = new ArrayList<>();\n for(int i = 0; i < edges.length; i++) {\n int e1 = edges[i][0];\n int e2 = edges[i][1];\n graph[e1].connected.add(e2);\n graph[e2].connected.add(e1);\n\n // Union\n if(!primes.contains(e1) && !primes.contains(e2)) {\n union(e1, e2, parents, uCounts);\n }\n }\n\n long result = 0;\n for(int i = 1; i <= n; i++) {\n if(primes.contains(i)) {\n // i became the root, compute the subtree rooted at i\n int total = 0;\n for(int j = 0; j < graph[i].connected.size(); j++) {\n total += sumNodesWrapper(graph[i].connected.get(j), i, graph, primes, counts, parents);\n }\n total++;\n for(int j = 0; j < graph[i].connected.size(); j++) {\n int tSum = sumNodesWrapper(graph[i].connected.get(j), i, graph, primes, counts, parents);\n result += (tSum * (total - tSum));\n total = total - tSum;\n }\n }\n }\n return result;\n }\n\n private int sumNodesWrapper(int s, int parent, Node[] graph, Set<Integer> primes, Map<Integer, Integer> counts, int[] parents) {\n int uParent = find(s, parents);\n if(counts.get(uParent) != null) return counts.get(uParent);\n counts.put(uParent, sumNodes(s, parent, graph, primes));\n return counts.get(uParent);\n }\n\n private int sumNodes(int s, int parent, Node[] graph, Set<Integer> primes) {\n if(primes.contains(s)) return 0;\n int sum = 0;\n Queue<Pair> q = new LinkedList<Pair>();\n q.add(new Pair(s, parent));\n while(!q.isEmpty()) {\n sum++;\n Pair elem = q.remove();\n for(int j = 0; j < graph[elem.val].connected.size(); j++) {\n if(!primes.contains(graph[elem.val].connected.get(j)) && elem.parent != graph[elem.val].connected.get(j)) {\n q.add(new Pair(graph[elem.val].connected.get(j), elem.val));\n }\n }\n }\n return sum;\n }\n\n private void union(int e1, int e2, int[] parents, int[] uCounts) {\n int pe1 = find(e1, parents);\n int pe2 = find(e2, parents);\n if(pe1 == pe2) return;\n if(uCounts[pe1] > uCounts[pe2]) {\n parents[pe2] = pe1;\n uCounts[pe1] += uCounts[pe2];\n\n } else {\n parents[pe1] = pe2;\n uCounts[pe2] += uCounts[pe1];\n }\n }\n\n private int find(int e, int[] parents) {\n int i = e;\n if(parents[i] != i) {\n i = find(parents[i], parents);\n parents[i] = i;\n }\n return parents[i];\n }\n\n private Set<Integer> getPrimes(int n) {\n Set<Integer> primes = new HashSet<>();\n\n for(int i = 2; i <= n; i++) primes.add(i);\n for(int i = 2; i*i <= n; i++) {\n if(primes.contains(i)) {\n for(int p = i*i; p <= n; p = p + i) {\n primes.remove(p);\n }\n }\n }\n return primes;\n }\n\n class Node {\n int val;\n List<Integer> connected;\n\n Node() {\n connected = new ArrayList<>();\n }\n }\n\n class Pair {\n int val;\n int parent;\n\n Pair(int val, int parent) {\n this.val = val;\n this.parent = parent;\n }\n }\n}\n```
0
0
['Java']
0
count-valid-paths-in-a-tree
Go solution || Beat 100%
go-solution-beat-100-by-constantinejin-94c1
Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nconst mx = 1e5 + 1\n\nvar isPrime [mx]bool\n\nfunc init() {\n\tvar primes []int\n\t
ConstantineJin
NORMAL
2024-02-27T09:59:17.885775+00:00
2024-02-27T09:59:17.885808+00:00
4
false
# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nconst mx = 1e5 + 1\n\nvar isPrime [mx]bool\n\nfunc init() {\n\tvar primes []int\n\tfor i := 2; i < mx; i++ {\n\t\tisPrime[i] = true\n\t}\n\tfor i := 2; i < mx; i++ {\n\t\tif isPrime[i] {\n\t\t\tprimes = append(primes, i)\n\t\t}\n\t\tfor _, prime := range primes {\n\t\t\tif i*prime >= mx {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tisPrime[i*prime] = false\n\t\t\tif i%prime == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc countPaths(n int, edges [][]int) int64 {\n\tvar g = make([][]int, n+1)\n\tfor _, edge := range edges {\n\t\tvar i, j = edge[0], edge[1]\n\t\tg[i] = append(g[i], j)\n\t\tg[j] = append(g[j], i)\n\t}\n\n\tvar dfs func(int, int)\n\tvar seen []int\n\tdfs = func(i, pre int) {\n\t\tseen = append(seen, i)\n\t\tfor _, j := range g[i] {\n\t\t\tif j != pre && !isPrime[j] {\n\t\t\t\tdfs(j, i)\n\t\t\t}\n\t\t}\n\t}\n\tvar ans int\n\tvar count = make([]int, n+1)\n\tfor i := 1; i <= n; i++ {\n\t\tif !isPrime[i] {\n\t\t\tcontinue\n\t\t}\n\t\tvar cur int\n\t\tfor _, j := range g[i] {\n\t\t\tif isPrime[j] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif count[j] == 0 {\n\t\t\t\tseen = []int{}\n\t\t\t\tdfs(j, 0)\n\t\t\t\tvar cnt = len(seen)\n\t\t\t\tfor _, k := range seen {\n\t\t\t\t\tcount[k] = cnt\n\t\t\t\t}\n\t\t\t}\n\t\t\tans += count[j] * cur\n\t\t\tcur += count[j]\n\t\t}\n\t\tans += cur\n\t}\n\treturn int64(ans)\n}\n```
0
0
['Go']
0
count-valid-paths-in-a-tree
[Python3] Easy to understand solution
python3-easy-to-understand-solution-by-d-bqbt
Just leaving it here:\n\nBuild the directed graph where prime nodes point to non-prime nodes, then for each prime node count number of all possible routes and t
dilshodbek
NORMAL
2024-02-10T12:32:14.420690+00:00
2024-02-10T12:36:46.901367+00:00
0
false
Just leaving it here:\n\nBuild the directed graph where prime nodes point to non-prime nodes, then for each prime node count number of all possible routes and their combinations. \n\nLet me know if you need any clarification/explanation. \n\n\n```\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n is_primes = [False]*2 + [True]*(n-1)\n for p in range(2,n+1):\n if is_primes[p]:\n for j in range(2*p,n+1,p):\n is_primes[j] = False\n @lru_cache(None)\n def returnPathes(node, prev):\n cur = 1\n for n in graph[node]:\n if n!=prev:\n cur+=returnPathes(n, node)\n return cur\n \n graph = collections.defaultdict(list)\n for a,b in edges:\n if is_primes[a]==False: graph[b].append(a)\n if is_primes[b]==False: graph[a].append(b)\n \n ans = 0\n for i in range(1, n+1):\n if is_primes[i]==False: continue\n poss = []\n for a in graph[i]:\n ret= returnPathes(a, -1)\n if ret!=0: poss.append(ret)\n s = sum(poss)\n ans+=sum(poss)\n sq = 0\n for i in poss: sq+=i**2\n ans+=(s**2-sq)//2\n return ans\n \n \n```
0
0
[]
0
count-valid-paths-in-a-tree
98.82% Fastest Prime Sieve + DFS + Combinatorics O(n*log(log(n))
9882-fastest-prime-sieve-dfs-combinatori-he6f
Submission Link: https://leetcode.com/submissions/detail/1161565654/\n\n# Approach\n- Set up Sieve of Eratosthenes in O(nlog(log(n))) time for O(1) later access
jasonpyau
NORMAL
2024-01-31T01:53:12.874760+00:00
2024-01-31T03:26:16.533660+00:00
5
false
Submission Link: https://leetcode.com/submissions/detail/1161565654/\n\n# Approach\n- Set up Sieve of Eratosthenes in O(n*log(log(n))) time for O(1) later access.\n- Create Graph\n- Run DFS, maintain accurate values, and run some combinatorics on each node\'s descendent.\n\n\n# Complexity\n- Time complexity:\nO(n*log(log(n))) For Sieve of Eratosthenes for Prime Numbers\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n // O(n*log(log(n))).\n long long countPaths(int n, vector<vector<int>>& edges) {\n sieve(n);\n vector<vector<int>> adj(n+1);\n // paths[v].first: Store number of paths you can make with 1 prime from\n // u to v and v\'s descendents, if u is non-prime.\n // paths[v].second: Store number of paths you can make with 0 primes from\n // u to v and v\'s descendents, if u is non-prime.\n vector<pair<int, int>> paths(n+1);\n for (vector<int>& edge : edges) {\n adj[edge[0]].push_back(edge[1]);\n adj[edge[1]].push_back(edge[0]);\n }\n // Just pick 1 to be root.\n return solve(1, 0, adj, paths);\n }\nprivate:\n vector<bool> prime;\n\n // O(n*log(log(n))).\n void sieve(int n) {\n prime = vector<bool>(n+1, true);\n prime[0] = prime[1] = false;\n for (int i = 2; 1ll*i*i <= n; ++i) {\n if (!prime[i]) {\n continue;\n }\n for (int j = 1ll*i*i; j <= n; j += i) {\n prime[j] = false;\n }\n }\n }\n\n long long solve(int u, int par, vector<vector<int>>& adj, vector<pair<int, int>>& paths) {\n pair<int, int>& path = paths[u];\n long long res = 0;\n for (int v : adj[u]) {\n if (v != par) {\n res += solve(v, u, adj, paths);\n path.first += paths[v].first;\n path.second += paths[v].second;\n }\n }\n // Two cases to consider, if u is prime or not prime.\n if (prime[u]) {\n // Connect u with all the paths with 0 primes.\n res += path.second;\n long long zero_to_zero = 0;\n for (int v : adj[u]) {\n if (v != par) {\n // Link paths with 0 primes with paths with 0 primes, as u is prime.\n zero_to_zero += 1ll*(path.second-paths[v].second)*paths[v].second;\n }\n }\n // We double counted each valid path.\n res += zero_to_zero/2;\n // All the paths with 0 primes becomes 1, also add a path ending with u.\n path.first = path.second+1;\n path.second = 0;\n } else {\n for (int v : adj[u]) {\n // Link paths with 1 prime with paths with 0 primes.\n if (v != par) {\n res += 1ll*(path.first-paths[v].first)*paths[v].second;\n }\n }\n // Connect u with all the paths with 1 prime.\n res += path.first;\n // Add a path ending with u.\n path.second += 1;\n }\n return res;\n }\n};\n```
0
0
['Depth-First Search', 'Combinatorics', 'Number Theory', 'C++']
0
count-valid-paths-in-a-tree
C++ Simple DFS O(nlogn)
c-simple-dfs-onlogn-by-user9107q-iqtm
\n\n# Approach\n- Compute primes using sieve\n- For each non prime node, compute number of nodes in connected component, bounded by either prime node or leaf no
user9107q
NORMAL
2024-01-03T17:50:43.407484+00:00
2024-01-03T17:51:16.657445+00:00
18
false
\n\n# Approach\n- Compute primes using sieve\n- For each non prime node, compute number of nodes in connected component, bounded by either prime node or leaf node\n- For each prime node, compute number of valid paths passing through this node \n\n\n# Code\n```\n#define ll long long\nclass Solution {\npublic:\n void sieve(vector<int> &prime, int n)\n {\n prime[1]=0;\n int i,j;\n for(i=2;i<=n;i++)\n {\n for( j=2;(i*j)<=n;j++)\n prime[i*j]=0;\n }\n }\n\n void dfs(vector<vector<int>> &adj, int i, vector<int> &prime, vector<int> &visited, int &cc, vector<int> &ccn)\n {\n visited[i]=1;\n cc+=1;\n ccn.push_back(i);\n for(auto k:adj[i])\n {\n if(prime[k]==0 && visited[k]==0)\n dfs(adj,k,prime,visited,cc,ccn);\n }\n }\n\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<int> prime(n+1,1);\n sieve(prime,n);\n vector<vector<int>> adj(n+1);\n int i,j;\n for(i=0;i<edges.size();i++)\n {\n adj[edges[i][0]].push_back(edges[i][1]);\n adj[edges[i][1]].push_back(edges[i][0]);\n }\n vector<int> visited(n+1,0);\n vector<int> ccs(n+1,0);\n for(i=1;i<=n;i++)\n {\n if(prime[i]==0 && visited[i]==0)\n {\n vector<int> temp;\n int cc=0;\n dfs(adj,i,prime,visited,cc,temp);\n for(auto k:temp)\n {\n ccs[k]=cc;\n }\n }\n }\n ll ans=0;\n for(i=1;i<=n;i++)\n {\n if(prime[i]==1)\n {\n ll s=0;\n for(auto k:adj[i])\n {\n s+=(ll)ccs[k];\n }\n ll s1=0;\n for(auto k:adj[i])\n {\n s1+=((ll)ccs[k]*((ll)s-(ll)ccs[k]));\n }\n ans+=s+s1/2;\n }\n }\n return ans;\n\n\n }\n};\n```
0
0
['Dynamic Programming', 'Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
Brute force optimized
brute-force-optimized-by-kingsenior-5g74
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
kingsenior
NORMAL
2024-01-02T16:46:31.971580+00:00
2024-01-02T16:46:31.971612+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> primes;\n void dfs(int rt,int pr,int &cnt,vector<vector<int>> &adj,vector<int> &ans){\n cnt++;\n for(auto &ch:adj[rt]){\n if(ch!=pr){\n if(primes[ch]){\n continue;\n }\n dfs(ch,rt,cnt,adj,ans);\n }\n }\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n primes = vector<int> (n+1,1);\n primes[0]=primes[1]=0;\n for(long long i=2;i<=n;i++){\n if(primes[i]==1){\n for(long long j=i*i;j<=n;j+=i){\n primes[j]=0;\n }\n }\n }\n vector<vector<int>> adj(n+1);\n for(auto x:edges){\n adj[x[0]].push_back(x[1]);\n adj[x[1]].push_back(x[0]);\n }\n\n long long anss=0;\n vector<int> subtree(n+1,-1);\n for(int i=2;i<=n;i++){\n if(primes[i]){\n primes[i]=0;\n vector<int> ans;\n cout<<i<<"\\n";\n for(auto ch:adj[i]){\n int cnt=0;\n if(!primes[ch] && subtree[ch]==-1){\n dfs(ch,i,cnt,adj,ans);\n subtree[ch]=cnt;\n }\n if(!primes[ch])ans.push_back(subtree[ch]);\n }\n primes[i]=1;\n long long l=0;\n for(auto x:ans) l+=x;\n long long p=0,q=0;\n for(auto x:ans){\n q+=x;\n p+= (l-q+1)*x;\n }\n anss+=p;\n }\n }\n\n return anss;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
O(N) time complecity C++ solution
on-time-complecity-c-solution-by-chan818-28ff
There are two paths to satisfy the question conditions.\n1. one endpoint is a prime, the other endpoint is not a prime\n2. both endpoints are not primes, the pa
chan818234
NORMAL
2023-12-30T09:33:30.190288+00:00
2023-12-30T12:00:13.351333+00:00
1
false
There are two paths to satisfy the question conditions.\n1. one endpoint is a prime, the other endpoint is not a prime\n2. both endpoints are not primes, the path cross a prime.\n\nA path between two primes doesn\'t help for this problem.\n\nTraversing each prime number, we can use the disjoint set to count the states of the non-prime numbers connected to each prime node to calculate the number of the two paths.\n```\n// <editor-fold defaultstate="collapsed" desc="#define OUT(...)">\n#ifndef OUT\n#define OUT(...)\n#endif\n// </editor-fold>\n\nconst int N = 1e5 + 10;\nbool np[N];\n\nconst auto primes = [] {\n np[0] = np[1] = true;\n vector<int> v;\n for (int i = 2; i < N; ++i) {\n if (!np[i]) v.push_back(i);\n for (int x: v) {\n int y = x * i;\n if (y >= N) break;\n np[y] = true;\n if (x % i == 0) break;\n }\n }\n return v;\n}();\n\nstruct Edge {\n int to;\n Edge *next;\n} container[N];\n\nvoid add(int a, int b, vector<Edge *> &head, int &top) {\n head[a] = &(container[top++] = Edge{\n .to = b,\n .next = head[a],\n });\n}\n\nclass DisjointSet {\n vector<int> father, cnt;\npublic:\n explicit DisjointSet(int n) : father(n), cnt(n, 1) {\n iota(father.begin(), father.end(), 0);\n }\n\n int getf(int x) { // NOLINT(misc-no-recursion)\n int &y = father[x];\n return x == y ? y : y = getf(y);\n }\n\n void merge(int x, int y) {\n x = getf(x), y = getf(y);\n if (x == y) return;\n father[x] = y;\n cnt[y] += cnt[x], cnt[x] = 0;\n }\n\n int operator[](int x) { return cnt[getf(x)]; }\n};\n\nint a[N];\n\nclass Solution {\npublic:\n static int64_t countPaths(int n, const vector<vector<int> > &edges) {\n assert(n == (int) edges.size() + 1);\n vector<Edge *> head(n + 1);\n DisjointSet ds(n + 1);\n for (int top = 0; auto &&e: edges) {\n int x = e[0], y = e[1];\n assert(1 <= x && x <= n);\n assert(1 <= y && y <= n);\n if (np[x]) {\n if (np[y]) ds.merge(x, y);\n else add(y, x, head, top);\n } else if (np[y]) {\n add(x, y, head, top);\n }\n }\n int64_t ans = 0;\n for (int x: primes) {\n if (x > n) break;\n int top = 0;\n for (auto p = head[x]; p; p = p->next) {\n int to = p->to;\n if (np[to]) a[top++] = ds[to];\n }\n OUT(x, vector(a, a + top));\n int64_t sum = accumulate(a, a + top, 0LL);\n int64_t t = 0;\n for (int i = 0; i < top; ++i) {\n int c = a[i];\n t += (sum - c) * c;\n }\n ans += sum + t / 2;\n }\n return ans;\n }\n};\n```
0
0
['Union Find']
0
count-valid-paths-in-a-tree
Only one DFS solution | C++
only-one-dfs-solution-c-by-hagoromo-1w8c
\n# Code\n\nclass Solution {\n vector<bool> sieve(int n){\n vector<bool> v(n+1,true);\n v[1]=false;\n for(int i=2;i*i<=n;i++){\n
Hagoromo
NORMAL
2023-12-10T10:37:32.697191+00:00
2023-12-10T10:37:32.697223+00:00
5
false
\n# Code\n```\nclass Solution {\n vector<bool> sieve(int n){\n vector<bool> v(n+1,true);\n v[1]=false;\n for(int i=2;i*i<=n;i++){\n if(v[i]==true){\n for(int j=i*2;j<=n;j+=i) v[j]=false;\n }\n }\n return v;\n }\n pair<int,int> dfs(vector<vector<int>>& graph,vector<bool>& prime,long long& ans,int i=1,int prev=-1){\n pair<int,int> paths={0,0};\n if(prime[i]) paths.first=1;\n else paths.second=1;\n for(int& j:graph[i]){\n if(j==prev) continue;\n pair<int,int> temp=dfs(graph,prime,ans,j,i);\n ans+=((long long)paths.first*(long long)temp.second)+((long long)paths.second*(long long)temp.first);\n if(prime[i]) paths.first+=temp.second;\n else{\n paths.first+=(temp.first);\n paths.second+=(temp.second);\n }\n }\n return paths;\n }\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n long long ans=0;\n vector<vector<int>> graph(n+1);\n for(int i=0;i<edges.size();i++){\n graph[edges[i][0]].push_back(edges[i][1]);\n graph[edges[i][1]].push_back(edges[i][0]);\n }\n vector<bool> prime=sieve(n);\n dfs(graph,prime,ans);\n return ans;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
[C++] DSU
c-dsu-by-quater_nion-rvb9
\nclass Solution {\n vector<int> parent;\n vector<int> size;\n int find(int a){\n return parent[a]==a ? a : parent[a] = find(parent[a]);\n }\
quater_nion
NORMAL
2023-11-14T18:56:03.024314+00:00
2023-11-14T18:56:03.024345+00:00
3
false
```\nclass Solution {\n vector<int> parent;\n vector<int> size;\n int find(int a){\n return parent[a]==a ? a : parent[a] = find(parent[a]);\n }\n void connect(int a, int b){\n int parentA = find(a);\n int parentB = find(b);\n if(parentA==parentB) return;\n if(size[parentA]>=size[parentB]){\n parent[parentB]=parentA;\n size[parentA]+=size[parentB];\n }else{\n parent[parentA]=parentB;\n size[parentB]+=size[parentA];\n }\n }\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<bool> isPrime(n+1, 1);\n vector<int> primes={};\n parent = vector<int>(n+1);\n size = vector<int>(n+1,1);\n for(int i=1; i<=n; i++)\n parent[i]=i;\n\n isPrime[0]=isPrime[1]=0;\n for(int i=2; i*i<=n; i++){\n if(isPrime[i]){\n for(int j=i*i; j<=n; j+=i)\n isPrime[j]=0;\n }\n }\n if(n>=2)\n primes.push_back(2);\n for(int i=3; i<=n; i+=2)\n if(isPrime[i]) \n primes.push_back(i);\n vector<vector<int>> graph(n+1);\n for(auto &e: edges){\n graph[e[0]].push_back(e[1]);\n graph[e[1]].push_back(e[0]);\n if((!isPrime[e[0]]) && (!isPrime[e[1]])){\n connect(e[0], e[1]);\n }\n }\n\n long long ans=0;\n for(auto &p: primes){\n vector<long long> vals={};\n for(auto &child: graph[p]) if(!isPrime[child]){\n long long s = size[parent[child]];\n if(s){\n ans+=s;\n vals.push_back(s);\n }\n }\n\n if(!vals.size()) continue;\n long long left = vals[0];\n for(int i=1; i<vals.size(); i++){\n ans+=left*vals[i];\n left+=vals[i];\n }\n }\n return ans;\n } \n};\n```
0
0
['Union Find', 'C++']
0
count-valid-paths-in-a-tree
DFS + Casework in O(n) (NO DSU OR LCA!)
dfs-casework-in-on-no-dsu-or-lca-by-gtsm-w1sb
Intuition\n Describe your first thoughts on how to solve this problem. \nUnfortunately, I was not clever enough to come up with a slick LCA or DSU algo. I just
gtsmarmy
NORMAL
2023-10-12T18:28:52.720743+00:00
2023-10-14T22:39:18.725911+00:00
21
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUnfortunately, I was not clever enough to come up with a slick LCA or DSU algo. I just used casework (and a whole lot of that!) along with some simple maths.\n# Approach\n\nFirst, we use a sieve (any *fast* sieve works, I used Eratosthenes) to verify whether a number is prime or not.\n\nThen, we track the number of 0 prime paths and 1 prime paths rooted at any arbitrary node.\n\nWe consider four cases.\n\n* Prime root, prime child\n* Composite root, prime child\n* Prime root, composite child\n* Composite root, composite child\n\n### Case 1:\nPrime root, prime child.\n\nSuppose our child $\\color{orange} c$ has $\\color{lime} x$ 0 prime paths and $\\color{lime} y$ 1 prime paths, denoted by $\\color{lime} (x,y)$.\nThen, our parent clearly cannot have any 1 prime paths **passing through child $\\color{orange} c$**, since both parent and child are prime. It also cannot have any 0 prime paths since every path rooted at parent will have a prime in it since parent is a prime.\n\nTherefore, the contribution from child $\\color{orange} c$ will be $\\color{magenta} (0,0)$\n\n### Case 2:\nComposite root, prime child.\n\nLet prime child $\\color{orange} c$ have $\\color{lime} (x,y)$ 0 and 1 prime paths, respectively.\nThen since child is prime, the number of 0 prime paths passing through it must be 0.\nSince parent is composite, the number of 1 prime paths passing through child is $\\color{tan} y+1$ \n\nTherefore, the contribution from child $\\color{orange} c$ will be $\\color{magenta} (0,y+1)$\n\n### Case 3:\nPrime root, composite child.\n\nLet composite child $\\color{orange} c$ have $\\color{lime} (x,y)$ 0 and 1 prime paths, respectively.\nThen since child is composite and parent is prime, the number of 1 prime paths passing through it must be $\\color{tan} x+1$.\nSince parent is prime, the number of 0 prime paths passing through child is $\\color{tan} 0$. \n\nTherefore, the contribution from child $\\color{orange} c$ will be $\\color{magenta} (0,x+1)$\n\n### Case 4:\nComposite root, composite child.\n\nLet composite child $\\color{orange} c$ have $\\color{lime} (x,y)$ 0 and 1 prime paths, respectively.\nThen since child is composite and parent is composite, the number of 1 prime paths passing through it must be $y$ (we don\'t change it).\nSince parent is composite, the number of 0 prime paths passing through child is $\\color{tan} x+1$\n\nTherefore, the contribution from child $\\color{orange} c$ will be $\\color{magenta} (x+1,y)$ \n \nGreat, but now we need to take care of those crossing paths that go from one subtree into another.\n### Crossing paths\nThe idea is that we again do casework (I know, why so much?)\n\n### Case 1:\nRoot is prime:\n\n![image.png](https://assets.leetcode.com/users/images/0991ce4f-f67c-4eb9-bcdb-726452284762_1697134012.5937388.png)\n\n\nIf this is the case, we know that our "left" side of the path and "right" side of the path must have 0 prime nodes in them. Luckily, we know the number of 0 prime paths rooted at any child. Let\'s take two arbitrary children $\\large \\color{pink} c_1,c_2$, then the number of crossing paths from $\\Large \\color{pink} c_1 \\to \\text{prime root} \\to c_2$ will be $\\color{5AFFA0} \\large p_0[c_1] \\cdot p_0[c_2]$, because each path in $\\large \\color{5AFFA0} c_1$ has $\\large \\color{5AFFA0} p_0[c_2]$ possible end nodes to create a valid path.\n\nSo what we do is calculate the sum over all pairwise products.\n\n$$\\color{5aa0ff} \\huge \\sum\\limits_{c_1,c_2 \\in \\text{adj}[r]} p_0[c_1] \\cdot p_0[c_2]$$\nThe way to do this in $\\color{turquoise} O(n)$ is to basically simplify the sum as follows:\n\n\n$$\\color{5aa0ff} \\Large \\sum\\limits_{c_1,c_2 \\in \\text{adj}[r]} p_0[c_1] \\cdot p_0[c_2] = \\sum\\limits_{i=0}^n \\sum\\limits_{j=i+1}^n p_0[c_i] \\cdot p_0[c_j]$$\n$$\\color{5aa0ff} \\Large = \\sum\\limits_{i=0}^n p_0[c_i] \\cdot \\sum\\limits_{j=i+1}^n p_0[c_j]$$\nand that inner sum can be evaluated in $$\\color{turquoise} O(1)$$ with prefix sums.\n\n### Case 2:\nRoot is composite:\n\nIn this case, we wish to have one side of the path contain 1 prime and the other contain 0 primes. This is similar to Case 1, but this time we multiply by $\\color{5AFFA0} \\large p_1[c_1] \\cdot p_0[c_2]$, which signifies $\\Large \\color{pink} c_1 \\to \\text{composite root} \\to c_2$.\n\nWe do a similar thing as Case 1, but we take extra care.\n\n# Complexity\n- Time complexity:\n$$\\color{turquoise} O(n \\log \\log n)$$\n\n- Space complexity:\n$$\\color{turquoise} O(n)$$\n\n# Code\n`spf[v] == v` is a way to check if prime (a prime is its own **smallest prime factor**).\n`spf[v] < v` means composite, as the **smallest prime factor** of $v$ is less than $v$\n```\ntypedef long long ll;\ntypedef vector<int> vi;\nconst int MAXN = (int) 1e5 + 7;\nclass Solution {\npublic:\n\nll spf[(int) 1e5 + 10]; \nvoid sieve(ll n){\n for (int i = 1; i <= n; ++i)\n spf[i] = i & 1 ? i : 2;\n for (int i = 3; i*i <= n; ++i){\n if (spf[i] == i){\n for (int p = i*i; p <= n; p += i) {\n if (spf[p] == p)\n spf[p] = i;\n }\n }\n }\n}\n\n\nll p1[MAXN];\nll p0[MAXN];\nvi adj[MAXN];\n\nvoid dfs(int v, int p, ll &ans) {\n vi a0, a1;\n for (auto c: adj[v]) {\n if (c == p)\n continue;\n dfs(c, v, ans);\n if (spf[v] == v && spf[c] < c) {\n p1[v] += p0[c] + 1;\n a0.emplace_back(p0[c] + 1);\n a1.emplace_back(0);\n } else if (spf[v] < v && spf[c] == c) {\n p1[v] += p1[c] + 1;\n a1.emplace_back(p1[c] + 1);\n a0.emplace_back(0);\n } else if (spf[v] < v && spf[c] < c) {\n p1[v] += p1[c];\n a1.emplace_back(p1[c]);\n p0[v] += p0[c] + 1;\n a0.emplace_back(p0[c] + 1);\n }\n\n }\n\n ans += p1[v];\n if (spf[v] == v) {\n ll s = accumulate(a0.begin(), a0.end(), 0);\n for (auto k: a0) {\n s -= k;\n ans += k * s;\n }\n } else {\n ll s = accumulate(a1.begin(), a1.end(), 0);\n for (int i = 0; i < a0.size(); ++i) {\n int k = a0[i];\n ans += k * (s - a1[i]);\n }\n }\n}\n\n long long countPaths(int n, vector<vector<int>>& e) {\n sieve((int) 1e5 + 3);\n // store 0 prime path cnt, 1 PP cnt\n\n // ROOT looks at children\n // if ROOT nonprime, \n for (auto c: e){\n adj[c[0]].emplace_back(c[1]);\n adj[c[1]].emplace_back(c[0]);\n }\n spf[1] = 0;\n ll ans = 0;\n dfs(1,0,ans);\n return ans;\n }\n};\n```
0
0
['Math', 'Depth-First Search', 'Recursion', 'C++']
0
count-valid-paths-in-a-tree
c++ tree-dp and dfs solution
c-tree-dp-and-dfs-solution-by-vedantnaud-lo0s
Intuition\n Describe your first thoughts on how to solve this problem. \nUse eratosthanes for is_prime array.\nfind the valid and non valid paths down a node in
vedantnaudiyal
NORMAL
2023-10-12T09:04:52.942377+00:00
2023-10-12T09:04:52.942400+00:00
15
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse eratosthanes for is_prime array.\nfind the valid and non valid paths down a node in the tree using dfs and a dp table starting from any node and then for each node find the horizontal paths passing through the node extending from one of the child branches to another.\n# Approach\n<!-- Describe your approach to solving the problem. -->\ntree-dp and dfs \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlog(n))\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1e5) ~ o(N)\n\n**PLS UPVOTE IF IT HELPED!**\nv -> valid paths \nnv -> non-valid paths \ndp[i][0]=valid paths down the node i and [1] for non-valid paths\np stands for the parent\'s perspective and c for child\'s perspective ie;\nvp -> valid paths from a branch rom parents perspective include that branch\'s contribution in valid paths of parent\nand\nvc -> valid paths can be formed by ending a non valid edge to any valid path edge node below the node i.(includes the node itself).\n# Code\n```\nclass Solution {\npublic:\nint is_prime[100001];\nlong long fun(int node,int par,vector<vector<int>>& adj,vector<vector<long long>>& dp){\n dp[node-1][1]=0;\n dp[node-1][0]=0;\n long long ans=0;\n long long sum_child_v=0;\n long long sum_child_nv=0;\n for(int i: adj[node]){\n if(i!=par){\n long long vp,nvp,vc,nvc;\n vp=0,nvp=0;\n ans+=fun(i,node,adj,dp);\n vc=dp[i-1][0]+((is_prime[i])?1:0);\n nvc=dp[i-1][1]+((!is_prime[i])?1:0);\n if(is_prime[node]){\n if(is_prime[i]==0){\n vp=1+dp[i-1][1];\n dp[node-1][0]+=1+dp[i-1][1];\n }\n }\n else{\n if(is_prime[i]){\n vp=1+dp[i-1][0];\n dp[node-1][0]+=1+dp[i-1][0];\n }\n else{\n vp=dp[i-1][0];\n dp[node-1][0]+=dp[i-1][0];\n nvp=1+dp[i-1][1];\n dp[node-1][1]+=1+dp[i-1][1];\n }\n }\n ans+=vp*(sum_child_nv);\n ans+=nvp*(sum_child_v);\n sum_child_v+=vc;\n sum_child_nv+=nvc;\n }\n }\n return dp[node-1][0]+ans;\n}\n long long countPaths(int n, vector<vector<int>>& edg) {\n memset(is_prime,1,sizeof(is_prime));\n is_prime[1]=is_prime[0]=0;\n for(int i=2;i<100001;i++){\n if(is_prime[i]){\n for(int x=2*i;x<100001;x+=i){\n is_prime[x]=0;\n }\n }\n }\n int e=edg.size();\n vector<vector<int>> adj(n+1);\n for(int i=0;i<e;i++){\n adj[edg[i][0]].push_back(edg[i][1]);\n adj[edg[i][1]].push_back(edg[i][0]);\n }\n vector<vector<long long>> dp(n,vector<long long>(2));\n long long ans=0;\n ans+=fun(1,-1,adj,dp);\n return ans;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
scala
scala-by-len_master-sjim
scala\nimport scala.collection.mutable\n\nobject Solution {\n private val MX: Int = 1e5.toInt\n private val np: Array[Boolean] = Array.ofDim[Boolean](MX + 1)\
len_master
NORMAL
2023-10-06T09:50:07.218183+00:00
2023-10-06T09:50:07.218203+00:00
1
false
``` scala\nimport scala.collection.mutable\n\nobject Solution {\n private val MX: Int = 1e5.toInt\n private val np: Array[Boolean] = Array.ofDim[Boolean](MX + 1)\n\n np(1) = true\n (2 to math.sqrt(MX).toInt)\n .withFilter(i => !np(i))\n .foreach(i => (i * i to MX by i)\n .foreach(j => np(j) = true))\n\n def countPaths(n: Int, edges: Array[Array[Int]]): Long = {\n val g = Array.fill(n + 1)(mutable.Buffer.empty[Int])\n edges.foreach(e => {\n val x = e.head\n val y = e(1)\n g(x).append(y)\n g(y).append(x)\n })\n\n var res = 0L\n val size = Array.ofDim[Int](n + 1)\n val nodes = mutable.Buffer.empty[Int]\n (1 to n)\n .withFilter(x => !np(x))\n .foreach(x => {\n var sum = 0\n g(x)\n .withFilter(y => np(y))\n .foreach(y => {\n if (size(y) == 0) {\n nodes.clear()\n f(y, -1, g, nodes)\n nodes.foreach(z => size(z) = nodes.size)\n }\n res += size(y).toLong * sum\n sum += size(y)\n })\n res += sum\n })\n res\n }\n\n private def f(x: Int, fa: Int, g: Array[mutable.Buffer[Int]], nodes: mutable.Buffer[Int]): Unit = {\n nodes.append(x)\n g(x)\n .withFilter(y => y != fa && np(y))\n .foreach(y => f(y, x, g, nodes))\n }\n}\n```
0
0
['Scala']
0
count-valid-paths-in-a-tree
Simple Solution Using DSU and DFS
simple-solution-using-dsu-and-dfs-by-wol-vgff
\n# Code\n\nstruct DSU{\n vector<int> par, size;\n DSU(int n){\n par.resize(n+1); size.resize(n+1, 1);\n for(int i=0;i<=n;i++) par[i] = i;\n
Wolfester
NORMAL
2023-10-04T07:47:43.935878+00:00
2023-10-04T07:47:43.935898+00:00
21
false
\n# Code\n```\nstruct DSU{\n vector<int> par, size;\n DSU(int n){\n par.resize(n+1); size.resize(n+1, 1);\n for(int i=0;i<=n;i++) par[i] = i;\n }\n int find(int a){\n if(par[a] == a) return a;\n return par[a] = find(par[a]);\n }\n void Union(int a, int b){\n a = find(a);\n b = find(b);\n\n if(a!=b){\n if(size[a]<size[b]) swap(a,b);\n par[b] = a;\n size[a]+=size[b];\n }\n }\n};\nvector<int> prime;\nclass Solution {\npublic:\n\n void count(int i, vector<vector<int>> &gr, vector<int>& vis, long long &ans, DSU& dsu){\n vis[i] = 1;\n for(auto x : gr[i]){\n if(vis[x]) continue;\n \n if(!prime[x]){\n vector<int> temp;\n for(auto c : gr[x]) if(prime[c]) temp.push_back(dsu.size[dsu.find(c)]);\n\n int sum = 0;\n for(auto c : temp) sum+=c;\n ans+=sum;\n for(auto c : temp){\n sum-=c;\n ans+=(1ll*c*sum);\n }\n }\n\n count(x, gr, vis, ans, dsu); \n }\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n\n prime.resize(n+1, 0);\n prime[1] = 1;\n for(int i=2;i<=n;i++){\n if(!prime[i]){\n for(int j=2*i;j<=n;j+=i){\n prime[j] = 1;\n }\n }\n }\n\n DSU dsu(n+1);\n\n\n vector<vector<int>> gr(n+1);\n for(auto x : edges){\n gr[x[0]].push_back(x[1]);\n gr[x[1]].push_back(x[0]); \n\n if(prime[x[0]] and prime[x[1]]) dsu.Union(x[1],x[0]);\n }\n\n \n vector<int> vis(n+1, 0);\n \n //for(int i=1;i<=n;i++) cout<<dsu.size[dsu.find(i)]<<" ";\n\n long long ans = 0;\n count(1, gr, vis, ans, dsu);\n\n return ans;\n }\n};\n```
0
0
['Depth-First Search', 'Union Find', 'C++']
0
count-valid-paths-in-a-tree
C++ || Crystal Clear Code
c-crystal-clear-code-by-raunakmishra1243-t2ih
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nhttps://leetcode.com/pr
raunakmishra1243
NORMAL
2023-10-02T23:36:56.687143+00:00
2023-10-02T23:36:56.687163+00:00
69
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[https://leetcode.com/problems/count-valid-paths-in-a-tree/solutions/4082775/dfs-tree-dp-in-c-java-python/](Reference )\nIn DFS/Tree DP, return 2 values:\n(1) The number of paths from root "goes down" that has no prime numbers, say A.\n(2) The number of paths from root "pass down" that has only one prime numbers, say B.\n\nIf root is a prime number then:\nroot_A = 0\nroot_B = sigma(A) via all childeren of root.\n\nIf root is not a prime number then:\nroot_A = sigma(A) via all childeren of root.\nroot_B = sigma(B) via all childeren of root.\n\nBefore updating root_A and root_B for each child\nwe add root_A * B + root_B * A to our final answer. That\'s the number of paths "pass through" and has only one prime number.\n\nHere "pass through" means the paths between the root\'s 2 descendants.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(N)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int>sieve;\n long long ans=0;\n void init(int n) {\n \n \n sieve = vector<int>(n + 1, true); \n sieve[0] = sieve[1] = false;\n for (int i = 2; i <= n; i++) {\n if (sieve[i]) {\n for (int j = i + i; j <= n; j += i) {\n sieve[j] = false;\n }\n }\n }\n }\n vector<int> dfs(int i, int par, vector<int>adj[])\n {\n vector<int>v(2,0);\n v[0]=sieve[i]?0:1; // no of ways with 0prime\n v[1]=sieve[i]?1:0; // no of ways with 1 prime\n for(auto j:adj[i])\n {\n if(j==par) continue;\n vector<int>child=dfs(j,i,adj);\n ans+=child[0]*v[1]+child[1]*v[0];\n if(sieve[i])\n {\n v[0]=0;\n v[1]+=child[0];\n }\n else\n {\n v[0]+=child[0];\n v[1]+=child[1];\n\n }\n\n\n }\n return v;\n }\n long long countPaths(int n, vector<vector<int>>& edges) \n {\n init(n);\n vector<int>adj[n+1];\n for(auto e:edges)\n {\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n\n }\n dfs(1,-1,adj);\n return ans;\n\n \n \n\n }\n};\n```
0
0
['C++']
1
count-valid-paths-in-a-tree
C# Union finder ,Sieve
c-union-finder-sieve-by-julian_meng_chan-thtc
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
julian_meng_chang
NORMAL
2023-10-02T01:46:32.595612+00:00
2023-10-02T01:46:32.595641+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n int[] P;\n List<int>[] D;\n int[,] parent;\n \n public long CountPaths(int n, int[][] edges) {\n P = Sieve(n); \n D = new List<int>[n+1];\n parent = new int[n+1,2];\n Dictionary<int,List<int>> Sets = new ();\n int[] I = new int[n+1];\n long res = 0;\n for(int i=1; i<=n; i++)\n {\n D[i] = new ();\n parent[i,0] = i;\n parent[i,1] = 1;\n }\n \n foreach(var edge in edges)\n {\n if(P[edge[1]]==0)\n D[edge[0]].Add(edge[1]);\n if(P[edge[0]]==0)\n D[edge[1]].Add(edge[0]); \n \n if( P[edge[0]]!=0 || P[edge[1]]!=0)\n continue;\n union(edge[0],edge[1]); \n }\n \n \n for(int i=1;i<=n;i++)\n {\n if(P[i]!=0) continue;\n int r = root(i);\n if(!Sets.ContainsKey(r))\n Sets[r] = new ();\n Sets[r].Add(i);\n I[i] = r;\n }\n \n for(int i=1;i<=n;i++)\n {\n if(I[i]>0)\n I[i] = Sets[I[i]].Count;\n }\n \n List<int> L = new ();\n for(int i=1;i<=n;i++)\n {\n if(P[i]!=0)\n {\n L.Clear();\n foreach(int node in D[P[i]])\n {\n L.Add(I[node]); \n }\n // Console.WriteLine($"prim: {prim}");\n res += Cal(L);\n }\n }\n \n \n return res;\n }\n \n private long Cal(List<int> N)\n {\n if(N.Count==0) return 0;\n long s = N.Sum();\n long s2 = s ;\n long res = s;\n for(int i=0;i<N.Count-1;i++)\n { \n s2 -= N[i];\n res += N[i] * s2;\n \n }\n //Console.WriteLine(res);\n return res;\n }\n //prim selection\n private int[] Sieve(int n){\n int[] pool = new int[n+1];\n for(int i=0; i<n+1; i++)\n pool[i] = i;\n pool[1] = 0;\n int m = (int)Math.Sqrt(n);\n for(int i=2;i<=m;i++)\n {\n int t = i*i;\n while(t<=n)\n {\n pool[t] = 0;\n t += i;\n }\n }\n \n \n return pool;\n }\n //union -finder\n private int root(int node)\n {\n while(parent[node,0]!=node) node = parent[node,0];\n return node;\n }\n \n private bool connected(int node1, int node2)\n => root(node1)==root(node2) ;\n //with depth as weight\n private void union(int node1, int node2)\n {\n int r1 = root(node1);\n int r2 = root(node2);\n if(parent[r1,1]>parent[r2,1])\n {\n parent[r2,0] = r1;\n }\n else if(parent[r1,1]==parent[r2,1])\n {\n parent[r2,0] = r1;\n parent[r1,1]++;\n }\n else\n parent[r1,0] = r2; \n }\n \n}\n```
0
0
['C#']
0
count-valid-paths-in-a-tree
Python | DFS | O(n)
python-dfs-on-by-aryonbe-jw5q
Code\n\nfrom collections import defaultdict\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n G = defaultdict(list)\n
aryonbe
NORMAL
2023-10-02T00:38:06.127559+00:00
2023-10-02T00:38:06.127590+00:00
13
false
# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n G = defaultdict(list)\n for u, v in edges:\n G[u].append(v)\n G[v].append(u)\n prime = [True]*(n+1)\n prime[1] = False\n for i in range(2, n + 1):\n if prime[i]:\n prime[i*i:n+1:i] = [False]*len(prime[i*i:n+1:i])\n res = 0\n def dfs(v, u):\n nonlocal res\n cur = [1 - prime[v], prime[v]]\n for w in G[v]:\n if w == u: continue \n nonPrimePath, primePath = dfs(w, v)\n res += nonPrimePath*cur[1] + primePath*cur[0]\n if prime[v]:\n cur[1] += nonPrimePath\n else:\n cur[0] += nonPrimePath\n cur[1] += primePath\n return cur \n dfs(1, 0)\n return res\n \n \n```
0
0
['Python3']
0
count-valid-paths-in-a-tree
C++ dfs down-to-top and top-to-down information flow
c-dfs-down-to-top-and-top-to-down-inform-qn3u
We first get information from the child up to the parent and then from the parent down to the child so that every node knows how many paths are there to leaves.
vvhack
NORMAL
2023-09-29T19:59:04.742867+00:00
2023-09-29T20:03:33.439632+00:00
8
false
We first get information from the child up to the parent and then from the parent down to the child so that every node knows how many paths are there to leaves.\nPlease note that "leaf" here refers to nodes that have no non-prime nodes.\nWe then go to every prime node and find out how many paths to leaves are there.\n```\nclass Solution {\npublic:\n long long n;\n vector<bool> isPrime;\n \n struct Node {\n bool prime = false;\n long long parent = -1;\n long long leafDistSum = 0;\n long long leafDistProdSum = 0;\n vector<int> neighbors;\n };\n vector<Node> tree;\n \n void populatePrimes() {\n for (long long p = 2; p <= n; ++p) {\n if (p > 2 && p % 2 == 0) continue;\n if (!isPrime[p]) continue;\n for (long long i = p * p; i <= n; i += p) {\n isPrime[i] = false;\n }\n }\n }\n \n void toChild(int nodeIdx) {\n auto& node = tree[nodeIdx];\n for (int neighborIdx : node.neighbors) {\n if (neighborIdx == node.parent) continue;\n auto& child = tree[neighborIdx];\n child.parent = nodeIdx;\n toChild(neighborIdx);\n if (child.prime) continue;\n long long extraLeafDistSum = (1 + child.leafDistSum);\n node.leafDistProdSum += (node.leafDistSum * extraLeafDistSum);\n node.leafDistSum += extraLeafDistSum;\n }\n }\n \n void fromParent(int nodeIdx) {\n auto& node = tree[nodeIdx];\n while (node.parent != -1) {\n auto& parent = tree[node.parent];\n if (parent.prime) break;\n if (node.prime) {\n long long extraLeafDistSum = (1 + parent.leafDistSum);\n node.leafDistProdSum += (node.leafDistSum * extraLeafDistSum);\n node.leafDistSum += extraLeafDistSum;\n } else {\n long long extraLeafDistSumFromChild =\n (1 + node.leafDistSum);\n long long extraLeafDistSum = (1 +\n (parent.leafDistSum -\n extraLeafDistSumFromChild));\n node.leafDistProdSum += (node.leafDistSum * extraLeafDistSum);\n node.leafDistSum += extraLeafDistSum;\n }\n break; \n }\n for (int neighborIdx : node.neighbors) {\n if (node.parent == neighborIdx) continue;\n auto& child = tree[neighborIdx];\n fromParent(neighborIdx);\n }\n }\n \n long long countPaths(int n, vector<vector<int>>& edges) {\n this->n = n;\n isPrime.resize(n + 1, true);\n isPrime[0] = false;\n isPrime[1] = false;\n populatePrimes();\n tree.resize(n + 1);\n for (int i = 0; i <= n; ++i) {\n if (isPrime[i]) {\n tree[i].prime = true;\n }\n }\n for (auto& edge : edges) {\n tree[edge[0]].neighbors.push_back(edge[1]);\n tree[edge[1]].neighbors.push_back(edge[0]);\n }\n long long tot = 0;\n toChild(1);\n fromParent(1);\n for (int i = 1; i <= n; ++i) {\n auto& node = tree[i];\n if (!node.prime) continue;\n tot += node.leafDistProdSum + node.leafDistSum;\n }\n return tot;\n }\n};\n```
0
0
[]
0
count-valid-paths-in-a-tree
Count Valid Paths in a Tree | C++ | Sieve | DFS | Clusters
count-valid-paths-in-a-tree-c-sieve-dfs-taxfz
Intuition\n Describe your first thoughts on how to solve this problem. \n1. Prime Number Sieve (Sieve of Eratosthenes):\n - Initially, it precomputes prime an
ArcticLights
NORMAL
2023-09-29T19:50:46.344561+00:00
2023-09-29T19:50:46.344592+00:00
35
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. **Prime Number Sieve (Sieve of Eratosthenes):**\n - Initially, it precomputes prime and non-prime numbers up to \'n\' using the Sieve algorithm.\n - This step is crucial to later identify which nodes in the graph are prime and non-prime efficiently.\n\n2. **Graph Traversal (Depth-First Search - DFS):**\n - The code uses DFS to traverse the graph and group connected non-prime nodes into clusters.\n - Each cluster represents a set of nodes that are not prime and are connected to each other.\n\n3. **Counting Paths within and between Clusters:**\n - After identifying clusters of non-prime nodes, the code counts the number of paths within each cluster.\n - The total number of paths within a cluster depends on the size of the cluster and its connections to other clusters.\n - The code accumulates these path counts to calculate the final result.\n\nWe first identify and groups non-prime nodes into clusters in the graph using DFS and then calculates the number of paths within and between these clusters. Then we use the Sieve algorithm to efficiently distinguish between prime and non-prime nodes.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nThe code implements a solution for counting the number of paths in a graph, subject to certain conditions. Here\'s a concise explanation of the approach:\n\n1. Sieve of Eratosthenes:\n - The `sieve` function initializes a boolean vector `is_prime` to mark prime numbers up to \'n\'.\n - It iterates through numbers from 2 to \'n\', marking non-prime numbers.\n - This sieve is used to identify prime and non-prime nodes later.\n\n2. Depth-First Search (DFS):\n - The `dfs` function performs a depth-first search on the graph, marking connected non-prime nodes with the same group identifier \'g\'.\n - It is used to identify clusters of connected non-prime nodes in the graph.\n\n3. Counting Paths:\n - The `countPaths` function initializes \'visited\' vector to mark visited nodes, \'graph\' to represent the input graph, and \'freq\' to count the sizes of clusters.\n - It iterates through nodes in the graph, running DFS on unvisited non-prime nodes and assigning them to different clusters.\n - It calculates the size of each cluster using \'freq\' and counts the total paths within each cluster.\n - The total paths within a cluster are determined by the number of nodes in that cluster and the total number of nodes in other clusters connected to it.\n - The results are accumulated to find the total count of paths satisfying the conditions.\n\n# Complexity\n- Time complexity: Please Comment-> (**It\'s Challenge**)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n+m)$$\n\n# Code\n```\nvector<bool> is_prime;\nbool ran = false;\n\nvoid sieve(int n)\n{\n ran = true;\n is_prime = vector<bool> (n + 1, true);\n is_prime[0] = is_prime[1] = false;\n for (int i = 2; i <= n; i++)\n {\n if (is_prime[i] && (long long)i * i <= n)\n {\n for (int j = i * i; j <= n; j += i)\n is_prime[j] = false;\n }\n }\n}\n\nclass Solution {\npublic:\n vector<int> visited;\n vector<vector<int>> graph;\n\n void dfs(int i,int &g)\n {\n visited[i] = g;\n for(int j:graph[i])\n {\n if(visited[j]==-1 && is_prime[j]==false)\n {\n dfs(j,g);\n }\n }\n }\n\n long long countPaths(int n, vector<vector<int>> &edges)\n {\n if(ran==false)\n sieve(1e5 + 10);\n\n graph = vector<vector<int>> (n + 1);\n\n for (auto i : edges)\n {\n graph[i[0]].push_back(i[1]);\n graph[i[1]].push_back(i[0]);\n }\n\n visited = vector<int> (n+1,-1);\n\n int gp = 1;\n for(int i=1;i<=n;i++)\n {\n if(visited[i]==-1 && is_prime[i]==false)\n {\n dfs(i,gp);\n gp++;\n }\n }\n\n unordered_map<int,int> freq;\n for(int i:visited)\n if(i!=-1)\n freq[i]++;\n\n\n long long ans = 0;\n\n for(int i=1;i<=n;i++)\n {\n if(visited[i]==-1)\n {\n vector<int> clusters;\n\n long long tot = 0;\n for(int j:graph[i])\n {\n if(visited[j]!=-1)\n {\n clusters.push_back(freq[visited[j]]);\n tot+=freq[visited[j]];\n }\n }\n\n long long cs = 0;\n long long ps = tot;\n for(int j=0;j<clusters.size();j++)\n {\n cs+= clusters[j];\n ps+= clusters[j] * (tot - cs);\n }\n\n ans+=ps;\n }\n }\n return ans;\n }\n};\n```
0
0
['Dynamic Programming', 'Tree', 'Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
AAHHHHHH | Video Walkthrough | Python
aahhhhhh-video-walkthrough-python-by-bnc-rt76
Click Here For Video Walkthrough\n\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n #n, m = len(edges)\n #SPAC
bnchn
NORMAL
2023-09-28T18:53:49.981444+00:00
2023-09-28T18:53:49.981472+00:00
16
false
[Click Here For Video Walkthrough](https://youtu.be/8YNvhcQB_mM)\n```\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n #n, m = len(edges)\n #SPACE: O(n+ m)\n #TIME: O(n* log(log(n)) + m + n)\n res = 0\n \n def isPrime(x):\n if x < 2: return 1\n for i in range(2,int(x ** (1/2))+1):\n if x % i == 0: return 1\n return 0\n \n V = [-1] * (n+1)\n \n \n T = [[] for _ in range(n+1)]\n for u,v in edges:\n T[u].append(v)\n T[v].append(u)\n if V[u] == -1: V[u] = isPrime(u)\n if V[v] == -1: V[v] = isPrime(v)\n \n \n def dfs(u,p=None):\n if V[u] == 1:\n return 1 + sum([dfs(v,u) for v in T[u] if v != p])\n return 0\n def col(u,c,p=None):\n if V[u] == 1:\n V[u] = c\n for v in T[u]:\n if v != p:\n col(v,c,u)\n \n for u in range(1,n+1):\n if V[u] == 1: col(u,dfs(u))\n \n for u in range(1,n+1):\n if V[u] == 0:\n X = 0\n for v in T[u]:\n if V[v] != 0:\n res += V[v]\n res += V[v] * X\n X += V[v]\n \n return res\n \n```
0
1
['Python']
0
count-valid-paths-in-a-tree
Group non prime nodes + calculate combinations
group-non-prime-nodes-calculate-combinat-g1ym
idea : find the just non prime nodes connected to prime nodes and calculate combinations of path from each non prime nodes to other non prime nodes\n\nfirst cal
demon_code
NORMAL
2023-09-28T13:20:56.352905+00:00
2023-09-28T13:20:56.352926+00:00
11
false
idea : find the just non prime nodes connected to prime nodes and calculate combinations of path from each non prime nodes to other non prime nodes\n\nfirst calculate all prime number in range of n put it in a unordered_set\n\ncombine all nodes which do have have any link with prime nodes \nand assign rank (level of depth from prime nodes) and size of other connected non prime nodes \nupdate parents after each itrations\n\n![image](https://assets.leetcode.com/users/images/f23a2d60-43ec-439e-ac23-59d0e38c47ea_1695907237.413149.jpeg)\n\n\n\n``` how we calculate no of paths ```\n\n![image](https://assets.leetcode.com/users/images/32a203de-598e-4b51-a146-62886b686a12_1695907091.769103.jpeg)\n\n\n\n```\nclass Solution {\npublic:\n unordered_set<int> s;\n \n void prime(int n)\n {\n \n bool prime[n + 1];\n memset(prime, true, sizeof(prime));\n\n for (int p = 2; p * p <= n; p++) {\n \n if (prime[p] == true) {\n for (int i = p * p; i <= n; i += p)\n prime[i] = false;\n }\n }\n int c=0;\n // get all prime number in set\n for (int p = 2; p <= n; p++)\n if (prime[p])s.insert(p);\n \n }\n \n \n \n \n vector<int> par;\n vector<int>rank;\n vector<long long>size;\n \n int find(int u)\n {\n if(par[u]==u) return u;\n return find(par[u]);\n }\n \n \n \n void merge(int u, int v)\n {\n u=find(u);\n v=find(v);\n \n if(rank[u]<rank[v])\n {\n par[u]=v;\n size[v]+=size[u];\n }else if(rank[u]>rank[v])\n {\n par[v]=u;\n size[u]+=size[v];\n }else\n {\n rank[v]++;\n size[u]+=size[v];\n par[v]=u;\n }\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n prime(n);\n par.resize(n+1,0);\n rank.resize(n+1,0);\n size.resize(n+1,1);\n for(int i=1; i<=n; i++) par[i]=i;\n vector<vector<int>> g(n+1);\n for(auto i: edges)\n {\n int c=i[0];\n int d=i[1];\n g[c].push_back(d);\n g[d].push_back(c);\n if((s.find(c)!=s.end())|| (s.find(d)!=s.end())) continue;\n \n merge(c,d);\n }\n \n long long ans=0;\n \n for(int i=1; i<=n; i++)\n {\n if(s.find(i)==s.end()) continue;\n vector<long long> val;\n \n for(auto j: g[i])\n {\n \n if(s.find(j)!=s.end()) continue;\n val.push_back(size[find(j)]);\n }\n if(val.size()<1) continue;\n \n long long r=val[0];\n int prev=val[0];\n \n for(int k=1; k<val.size(); k++)\n {\n if(val[k]==0) continue;\n r+=val[k];\n r+=val[k]*prev;\n prev+=val[k];\n }\n// cout<<"hi\\n";\n \n \n ans+=r;\n }\n \n return ans;\n \n \n }\n};\n\n```
0
0
['Tree', 'Union Find']
0
count-valid-paths-in-a-tree
Sieve of Eratosthenes | dfs | dp
sieve-of-eratosthenes-dfs-dp-by-pr1yansh-thr7
Time complexity : O(NlogN)\n\n# Code\n\nclass Solution {\npublic:\n \n vector<long long> isPrime, dp;\n\n //dfs to find number of non prime nodes\n
pr1yanshu
NORMAL
2023-09-28T12:12:39.267184+00:00
2023-09-28T17:03:19.255491+00:00
13
false
**Time complexity :** **O(NlogN)**\n\n# Code\n```\nclass Solution {\npublic:\n \n vector<long long> isPrime, dp;\n\n //dfs to find number of non prime nodes\n long long dfs(vector<int>g[],int node, int par=-1){\n int count=1;\n for(auto &i: g[node]){\n if(i==par or isPrime[i])continue;\n count += dfs(g,i,node);\n }\n return count;\n }\n\n //all connected non prime nodes are memoized to reduce multiple dfs calls\n void set(vector<int>g[], int node, long long val, int par=-1){\n dp[node]=val;\n for(auto &i: g[node]){\n if(i==par or isPrime[i])continue;\n set(g,i,val,node);\n }\n }\n \n long long countPaths(int n, vector<vector<int>>& edges) {\n dp.resize(n+1, -1);\n isPrime.resize(n+1,1);\n isPrime[0]=0, isPrime[1]=0;\n vector<int> primes; // vector storing all prime nodes\n for(int i=2;i<=n;i++){\n if(!isPrime[i])continue;\n for(int j=2*i;j<=n;j+=i){\n isPrime[j]=0;\n }\n primes.push_back(i);\n }\n long long as=0;\n vector<int> g[n+1];\n for(auto i: edges){\n g[i[0]].push_back(i[1]);\n g[i[1]].push_back(i[0]);\n }\n for(auto &i: primes){ // traversing in prime nodes\n long long sum=0,tm=0;\n for(auto child: g[i]){\n if(isPrime[child])continue;\n long long vl=0;\n if(dp[child]!=-1){\n vl = dp[child];\n }\n else{\n vl = dfs(g,child);\n set(g,child, vl);\n }\n\n// let a prime node is surrounded by 1,3,3,4 non prime nodes.\n// So in total how many valid paths exists, paths that end or\n// start at our prime node and paths passing through our prime node.\n// { 1,3,3,4} = 1+3+3+4 + 1*3+ 1*3 + 1*4 +3*3 + 3*4 +3*4 \n\n sum += vl + tm*(vl); // pref sum method to calculate\n// sum of products of all pairs\n tm += vl;\n }\n as += sum;\n }\n return as;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
DSU + Seive beats 100% of the java solution : Complexity ~ O(n)
dsu-seive-beats-100-of-the-java-solution-7qu4
\nclass Solution {\n int []prime;\n int []sizes;\n int []parent;\n List<List<Integer>> tree;\n \n public void create(int n) {\n for(int
namandeept
NORMAL
2023-09-26T20:22:01.703871+00:00
2023-09-26T20:52:26.827591+00:00
7
false
```\nclass Solution {\n int []prime;\n int []sizes;\n int []parent;\n List<List<Integer>> tree;\n \n public void create(int n) {\n for(int i=1; i<=n; i++) {\n if(prime[i] == 0) {\n sizes[i] = 1;\n parent[i] = i;\n }\n }\n }\n \n public int find(int node) {\n if(node == parent[node]) return node;\n return parent[node] = find(parent[node]);\n }\n \n public void union(int node1, int node2) {\n node1 = find(node1);\n node2 = find(node2);\n if(node1 == node2) return;\n if(sizes[node1] > sizes[node2]) {\n parent[node2] = node1;\n sizes[node1] += sizes[node2];\n }\n else {\n parent[node1] = node2;\n sizes[node2] += sizes[node1];\n }\n }\n \n public void seive(int lim) {\n Arrays.fill(prime, 1);\n prime[1] = 0;\n for(int i=2; i*i <=lim; i++) {\n if(prime[i] == 1) {\n for(int j=i*i; j<=lim; j+=i) {\n prime[j] = 0;\n }\n } \n }\n }\n \n public void reset(int n) {\n prime = new int[n + 1];\n sizes = new int[n + 1];\n parent = new int[n + 1];\n tree = new ArrayList<>();\n for(int i=0; i<=n; i++) {\n tree.add(new ArrayList<>());\n }\n }\n \n public long countPaths(int n, int[][] edges) {\n reset(n);\n seive(n);\n create(n);\n \n for(int []edge : edges) {\n int n1 = edge[0], n2 = edge[1]; \n if(prime[n1] == 0 && prime[n2] == 0) {\n union(n1, n2);\n }\n tree.get(n1).add(n2);\n tree.get(n2).add(n1);\n }\n \n long sum = 0L;\n \n for(int i=1; i<=n; i++) {\n if(prime[i] == 1) {\n long total = 1L;\n int idx = 0;\n List<Integer> temp = new ArrayList<>();\n for(int children : tree.get(i)) {\n if(prime[children] == 0) {\n temp.add(sizes[find(children)]);\n total += temp.get(idx++);\n } \n }\n int sz = temp.size();\n for(int k=0; k<sz; k++) {\n total -= temp.get(k);\n sum += temp.get(k) * total;\n }\n }\n }\n return sum;\n }\n}\n\n```
0
0
[]
0
count-valid-paths-in-a-tree
A simple java dfs solution
a-simple-java-dfs-solution-by-dudadi-ac6o
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
dudadi
NORMAL
2023-09-26T11:31:48.621049+00:00
2023-09-26T11:31:48.621077+00:00
21
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n long total = 0l;\n public long countPaths(int n, int[][] edges) {\n boolean[] isPrimeArray = new boolean[n+1];\n for(int i=2;i<=n;i++) {\n isPrimeArray[i] = true;\n }\n for(int i=2;i<=n;i++) {\n if(isPrimeArray[i]) {\n for(long j=(long)i*i;j<=n;j+=i) {\n isPrimeArray[(int)(j% Integer.MAX_VALUE)] = false;\n }\n }\n }\n List<Integer>[] nexts = new List[n+1];\n for(int i=0;i<=n;i++) {\n nexts[i] = new ArrayList<>();\n }\n for(int[] edge: edges) {\n int u = edge[0], v = edge[1];\n nexts[u].add(v);\n nexts[v].add(u);\n }\n dfs(nexts, isPrimeArray, 1, -1);\n return total;\n }\n public int[] dfs(List<Integer>[] nexts, boolean[] isPrimeArray, int index, int pre) {\n // System.out.println("before: " + index + ", " + pre + ", " + total);\n List<Integer> next = nexts[index];\n int size = next.size();\n int[] res = new int[2];\n boolean isPrime = isPrimeArray[index];\n List<int[]> subResList = new ArrayList<>();\n for(int node: next) {\n if(node != pre) {\n int[] subRes = dfs(nexts, isPrimeArray, node, index);\n subResList.add(subRes);\n res[0] += subRes[0];\n res[1] += subRes[1];\n }\n }\n if(isPrime) {\n long cur = 0l;\n for(int[] subRes: subResList) {\n cur += (long)(res[0] - subRes[0]) * subRes[0];\n }\n total += cur / 2;\n total += res[0];\n res[1] = res[0] + 1;\n res[0] = 0;\n } else {\n for(int[] subRes: subResList) {\n total += (long)(res[0] - subRes[0]) * subRes[1];\n }\n res[0] = res[0] + 1;\n total += res[1];\n }\n // System.out.println("after: " + index + ", " + res[0] + ", " + res[1] + ", " + total);\n return res;\n }\n}\n```
0
0
['Backtracking', 'Java']
0
count-valid-paths-in-a-tree
DFS and maintaining no. of paths with 1 and 0 prime numbers
dfs-and-maintaining-no-of-paths-with-1-a-qkvp
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Code_Hard02
NORMAL
2023-09-25T22:16:19.181962+00:00
2023-09-25T22:16:19.181986+00:00
15
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n using ll = long long;\n long long ans=0;\n vector<int> dfs(int node,vector<int>&vis,unordered_map<int,vector<int>>&mp,vector<int> &prime){\n vector<int> cnt={0,0};\n cnt[prime[node]]++;\n vis[node]=1;\n for(auto it:mp[node]){\n vector<int>v={0,0};\n if(!vis[it]){\n v = dfs(it,vis,mp,prime);\n }\n ans+=1ll*cnt[0]*1ll*v[1];\n ans+=1ll*cnt[1]*1ll*v[0];\n cnt[prime[node]]+=v[0];\n if(prime[node]==0) cnt[1]+=v[1];\n }\n return cnt;\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<int> prime(n+1,true);\n for(int p=2;p*p<=n;p++){\n if(prime[p]==true){\n for(int i=p*p;i<=n;i+=p){\n prime[i]=false;\n }\n }\n }\n prime[1]=false;\n unordered_map<int,vector<int>>mp;\n for(auto it:edges){\n mp[it[0]].push_back(it[1]);\n mp[it[1]].push_back(it[0]);\n }\n vector<int>vis(n+1,0);\n dfs(1,vis,mp,prime);\n return ans;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
Rust DFS
rust-dfs-by-xiaoping3418-qt7h
Intuition\n Describe your first thoughts on how to solve this problem. \n1) Randam pick a node as the root, using DFS to calculate count = Vec<(i32, i32); n + 1
xiaoping3418
NORMAL
2023-09-25T22:06:47.929124+00:00
2023-09-29T22:33:34.889033+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1) Randam pick a node as the root, using DFS to calculate count = Vec<(i32, i32); n + 1>; where count[u] = (# of paths in the sub-tree with 0 primes starting from u, # of paths in the sub-tree with 1 prime starting from u).\n2) Assuming u is the root of a new tree, performance another DFS to calculate data[u] = (# of paths in the sub-tree with 0 primes starting from u, # of paths in the sub-tree with 1 prime starting from u).\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\nstruct Helper {\n primes: Vec<usize>,\n graph: Vec<Vec<usize>>,\n count: Vec<(i32, i32)>\n}\n\nimpl Helper {\n fn new(edges: Vec<Vec<i32>>) -> Self {\n let mut primes = vec![];\n for i in 2 .. 1000 {\n if i * i > 100000 { break }\n let mut flag = 1;\n for p in &primes {\n if i % (*p) != 0 { continue }\n flag = 0;\n break\n }\n if flag == 1 { primes.push(i); }\n }\n\n let n = edges.len() + 2;\n let mut graph = vec![vec![]; n];\n for e in edges {\n let (u, v) = (e[0] as usize, e[1] as usize);\n graph[u].push(v);\n graph[v].push(u);\n }\n Self { primes, graph, count: vec![(0, 0); n] }\n }\n\n fn prime(&self, i: usize) -> bool {\n if i == 1 { return false }\n for p in &self.primes {\n if *p >= i { break }\n if i % (*p) == 0 { return false }\n }\n true\n }\n\n fn dfs(&mut self, u: usize, p: usize, zero_cnt: &mut i32, one_cnt: &mut i32) {\n let (mut cnt1, mut cnt2) = (0, 0);\n \n for v in self.graph[u].clone() {\n if v == p { continue }\n\n let (mut c1, mut c2) = (0, 0);\n self.dfs(v, u, &mut c1, &mut c2);\n cnt1 += c1;\n cnt2 += c2;\n }\n\n if self.prime(u) {\n self.count[u] = (0, cnt1);\n *zero_cnt = 0;\n *one_cnt = cnt1 + 1;\n } else {\n self.count[u] = (cnt1, cnt2);\n *zero_cnt = cnt1 + 1;\n *one_cnt = cnt2;\n }\n }\n\n fn re_root(&self, u: usize, p: usize, data: &mut Vec<(i32, i32)>) {\n data[u] = self.count[u];\n if p != 0 {\n let (b1, b2) = (self.prime(u), self.prime(p));\n if !b1 && !b2 { data[u] = data[p]; }\n if !b1 && b2 { data[u].1 += data[p].1 - self.count[u].0; }\n if b1 && !b2 { data[u].1 += data[p].0 + 1 }\n }\n \n for v in self.graph[u].clone() {\n if v != p { self.re_root(v, u, data); }\n }\n }\n }\n\nimpl Solution {\n pub fn count_paths(n: i32, edges: Vec<Vec<i32>>) -> i64 {\n let mut h = Helper::new(edges);\n let (mut zero_cnt, mut one_cnt) = (0, 0);\n h.dfs(1, 0, &mut zero_cnt, &mut one_cnt);\n\n let mut data = vec![(0, 0); n as usize + 1];\n h.re_root(1, 0, &mut data);\n \n let mut ret = 0;\n for d in data { ret += d.1 as i64; }\n\n ret / 2\n }\n}\n```
0
0
['Rust']
0
count-valid-paths-in-a-tree
C++ | dp on trees + sieve
c-dp-on-trees-sieve-by-harsh_malik-ocpv
\n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \n\nN logN\n\n\n- Space complexity:\n Add your space complexity here, e.g. O(n) \n
harsh_malik_
NORMAL
2023-09-25T17:08:31.526326+00:00
2023-09-25T17:08:31.526347+00:00
39
false
\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n```\nN logN\n```\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n```\n4*N\n```\n\n# Code\n```\n#define ll long long\nconst int N = 1e5 + 5 ; \n\nclass Solution {\npublic:\n bool isprime[N+1] ;\n void init(){\n memset(isprime , 1 , sizeof(isprime)) ;\n isprime[1] = 0 ; \n for(int i = 2 ; i * i <= N ; ++i ){\n for(int j = i * i ; j <= N ; j += i ){\n isprime[j] = 0 ; \n }\n }\n // for(int i = 2 ; i <= 20 ; ++i ){cout<<isprime[i]<<" " ;}\n }\n\n\n vector<vector<int>> adj ;\n ll dp[N][2] ;\n vector<bool> vis ;\n \n void dfs(int src ){\n vis[src] = 1 ;\n ll zero = 0 , one = 0 ;\n for(auto it : adj[src] ){\n if(!vis[it]){\n dfs(it) ;\n zero += dp[it][0] ;\n one += dp[it][1] ;\n }\n }\n if(isprime[src+1] ){\n dp[src][0] = 0 ;\n dp[src][1] = zero + (ll)1 ;\n }\n else{\n dp[src][0] = zero + (ll)1 ;\n dp[src][1] = one ;\n }\n vis[src] = 0 ; \n }\n\n ll ans[N] ;\n void dfs2(int src ){\n\n vis[src] = 1 ;\n ll zero = 0 , one = 0 ;\n ans[src] = dp[src][1] ;\n if(isprime[src+1] ) --ans[src] ;\n\n for(auto it : adj[src] ){\n if(!vis[it]){\n dfs2(it ) ;\n zero += dp[it][0] ;\n one += dp[it][1] ;\n ans[src] += ans[it] ;\n }\n }\n ll cnt = 0 ; \n for(auto it : adj[src] ){\n if(!vis[it]){\n if( !isprime[src+1] ){\n cnt += (one - dp[it][1])*dp[it][0] ;\n cnt += (zero - dp[it][0])*dp[it][1] ;\n }\n else{\n cnt += (zero - dp[it][0])*dp[it][0] ;\n }\n }\n }\n cnt = cnt / 2 ;\n ans[src] += cnt ;\n \n vis[src] = 0 ;\n }\n\n long long countPaths(int n, vector<vector<int>>& edges) {\n init() ;\n\n adj.clear() ;\n adj.resize(n) ;\n for(auto it : edges ){\n adj[it[0]-1].push_back(it[1]-1) ;\n adj[it[1]-1].push_back(it[0]-1) ;\n }\n memset(dp , 0 , sizeof(dp)) ;\n\n vis.clear() ;\n vis.resize(n, 0 ) ;\n \n dfs(0) ;\n memset(ans , 0 , sizeof(ans)) ;\n dfs2(0) ;\n\n // for(int i = 0 ; i < n ; ++i ){\n // cout<<dp[i][0] <<" "<<dp[i][1]<<endl;\n // }\n // for(int i = 0 ; i < n ; ++i ) cout<<ans[i]<<" ";\n // cout<<endl;\n\n ll cnt = ans[0] ;\n return cnt ;\n }\n};\n```
0
0
['Dynamic Programming', 'Tree', 'Number Theory', 'C++']
0
count-valid-paths-in-a-tree
My Solutions
my-solutions-by-hope_ma-u7dm
1. Use the Sieve of Eratosthenes Algorithm to get all prime numbers from 1 to n, and then use the DP\n\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(n)
hope_ma
NORMAL
2023-09-25T15:46:11.603049+00:00
2023-09-26T03:10:02.084902+00:00
6
false
**1. Use the `Sieve of Eratosthenes` Algorithm to get all prime numbers from `1` to `n`, and then use the DP**\n```\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n */\nclass Solution {\n private:\n /**\n * <first>: the number of paths which contain just one node whose label is a prime number\n * <second>: the number of paths which don\'t contain any nodes whose labels are prime numbers\n */\n using stat_t = pair<int, int>;\n \n static constexpr int root = 0;\n static constexpr int invalid_parent = -1;\n \n public:\n long long countPaths(const int n, const vector<vector<int>> &edges) {\n bool is_prime[n];\n populate_is_prime(is_prime, n);\n \n vector<int> graph[n];\n for (const vector<int> &edge : edges) {\n graph[edge.front() - 1].emplace_back(edge.back() - 1);\n graph[edge.back() - 1].emplace_back(edge.front() - 1);\n }\n \n long long ret = 0LL;\n dfs(is_prime, graph, root, invalid_parent, ret);\n return ret;\n }\n \n private:\n void populate_is_prime(bool *is_prime, const int n) {\n memset(is_prime, 0x01, sizeof(bool) * n);\n is_prime[0] = false;\n for (int i = 2; i < n + 1; ++i) {\n if (is_prime[i - 1]) {\n for (int j = i; j < n / i + 1; ++j) {\n is_prime[i * j - 1] = false;\n }\n }\n }\n }\n \n /**\n * @return: a pair\n * <first>: the number of paths which contain just one node whose label is a prime number\n * <second>: the number of paths which don\'t contain any nodes whose labels are prime numbers\n * where every path is starting from the node `node` and\n * ending with any nodes which are the descendants of the node `node`,\n * including itself\n */\n stat_t dfs(const bool *is_prime,\n const vector<int> *graph,\n const int node,\n const int parent,\n long long &result) {\n vector<pair<int, int>> stats;\n /**\n * `total_prime_count` is the number of the paths\n * which contains just one node whose label is a prime number, and\n * starts from any one of the children of the node `node`\n */\n int total_prime_count = 0;\n /**\n * `total_non_prime_count` is the number of the paths\n * which don\'t contain any nodes whose labels are prime numbers, and\n * starts from any one of the children of the node `node`\n */\n int total_non_prime_count = 0;\n for (const int child : graph[node]) {\n if (child == parent) {\n continue;\n }\n \n const pair<int, int> stat = dfs(is_prime, graph, child, node, result);\n total_prime_count += stat.first;\n total_non_prime_count += stat.second;\n stats.emplace_back(move(stat));\n }\n \n if (stats.empty()) {\n return make_pair(is_prime[node] ? 1 : 0, is_prime[node] ? 0 : 1);\n }\n\n int prime_count = 0;\n int non_prime_count = 0;\n const int n_stats = static_cast<int>(stats.size());\n /**\n * if the node `node` has the label of a prime number,\n * `result_prime_count` is the number of the paths\n * which contain just one node whose label is a prime number, and\n * starts from one child node, and ends with another child node;\n * otherwise it\'s zero\n */\n long long result_prime_count = 0LL;\n /**\n * if the node `node` has the label of a non-prime number,\n * `result_non_prime_count` is the number of the paths\n * which contain just one node whose label is a prime number, and\n * starts from one child node, and ends with another child node;\n * otherwise it\'s zero\n */\n long long result_non_prime_count = 0LL;\n for (int i = 0; i < n_stats; ++i) {\n const auto [item_prime_count, item_non_prime_count] = stats[i];\n prime_count += is_prime[node] ? item_non_prime_count : item_prime_count;\n non_prime_count += is_prime[node] ? 0 : item_non_prime_count;\n if (is_prime[node]) {\n result_prime_count += item_non_prime_count * (total_non_prime_count - item_non_prime_count);\n } else {\n result_non_prime_count += item_prime_count * (total_non_prime_count - item_non_prime_count);\n }\n }\n result += prime_count + (result_prime_count >> 1) + result_non_prime_count;\n prime_count += is_prime[node] ? 1 : 0;\n non_prime_count += is_prime[node] ? 0 : 1;\n return make_pair(prime_count, non_prime_count);\n }\n};\n```\n**2. Use the `Linear Sieve` (`Euler\'s Sieve`) Algorithm to get all prime numbers from `1` to `n`, and then use the DP**\n```\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n */\nclass Solution {\n private:\n /**\n * <first>: the number of paths which contain just one node whose label is a prime number\n * <second>: the number of paths which don\'t contain any nodes whose labels are prime numbers\n */\n using stat_t = pair<int, int>;\n \n static constexpr int root = 0;\n static constexpr int invalid_parent = -1;\n \n public:\n long long countPaths(const int n, const vector<vector<int>> &edges) {\n bool is_prime[n];\n populate_is_prime(is_prime, n);\n \n vector<int> graph[n];\n for (const vector<int> &edge : edges) {\n graph[edge.front() - 1].emplace_back(edge.back() - 1);\n graph[edge.back() - 1].emplace_back(edge.front() - 1);\n }\n \n long long ret = 0LL;\n dfs(is_prime, graph, root, invalid_parent, ret);\n return ret;\n }\n \n private:\n void populate_is_prime(bool *is_prime, const int n) {\n memset(is_prime, 0x01, sizeof(bool) * n);\n vector<int> primes;\n is_prime[0] = false;\n for (int i = 2; i < n + 1; ++i) {\n if (is_prime[i - 1]) {\n primes.emplace_back(i);\n }\n for (const int p : primes) {\n if (p * i > n) {\n break;\n }\n is_prime[p * i - 1] = false;\n if (i % p == 0) {\n // `p` is the least prime factor of `i`\n break;\n }\n }\n }\n }\n \n /**\n * @return: a pair\n * <first>: the number of paths which contain just one node whose label is a prime number\n * <second>: the number of paths which don\'t contain any nodes whose labels are prime numbers\n * where every path is starting from the node `node` and\n * ending with any nodes which are the descendants of the node `node`,\n * including itself\n */\n stat_t dfs(const bool *is_prime,\n const vector<int> *graph,\n const int node,\n const int parent,\n long long &result) {\n vector<pair<int, int>> stats;\n /**\n * `total_prime_count` is the number of the paths\n * which contains just one node whose label is a prime number, and\n * starts from any one of the children of the node `node`\n */\n int total_prime_count = 0;\n /**\n * `total_non_prime_count` is the number of the paths\n * which don\'t contain any nodes whose labels are prime numbers, and\n * starts from any one of the children of the node `node`\n */\n int total_non_prime_count = 0;\n for (const int child : graph[node]) {\n if (child == parent) {\n continue;\n }\n \n const pair<int, int> stat = dfs(is_prime, graph, child, node, result);\n total_prime_count += stat.first;\n total_non_prime_count += stat.second;\n stats.emplace_back(move(stat));\n }\n \n if (stats.empty()) {\n return make_pair(is_prime[node] ? 1 : 0, is_prime[node] ? 0 : 1);\n }\n\n int prime_count = 0;\n int non_prime_count = 0;\n const int n_stats = static_cast<int>(stats.size());\n /**\n * if the node `node` has the label of a prime number,\n * `result_prime_count` is the number of the paths\n * which contain just one node whose label is a prime number, and\n * starts from one child node, and ends with another child node;\n * otherwise it\'s zero\n */\n long long result_prime_count = 0LL;\n /**\n * if the node `node` has the label of a non-prime number,\n * `result_non_prime_count` is the number of the paths\n * which contain just one node whose label is a prime number, and\n * starts from one child node, and ends with another child node;\n * otherwise it\'s zero\n */\n long long result_non_prime_count = 0LL;\n for (int i = 0; i < n_stats; ++i) {\n const auto [item_prime_count, item_non_prime_count] = stats[i];\n prime_count += is_prime[node] ? item_non_prime_count : item_prime_count;\n non_prime_count += is_prime[node] ? 0 : item_non_prime_count;\n if (is_prime[node]) {\n result_prime_count += item_non_prime_count * (total_non_prime_count - item_non_prime_count);\n } else {\n result_non_prime_count += item_prime_count * (total_non_prime_count - item_non_prime_count);\n }\n }\n result += prime_count + (result_prime_count >> 1) + result_non_prime_count;\n prime_count += is_prime[node] ? 1 : 0;\n non_prime_count += is_prime[node] ? 0 : 1;\n return make_pair(prime_count, non_prime_count);\n }\n};\n```\n**3. Use the `Sieve of Eratosthenes` Algorithm to get all prime numbers from `1` to `n`, and then use the Disjoint Set**\n```\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n */\nclass Solution {\n private:\n class DisjointSet {\n public:\n DisjointSet(const int n) : parents_(n), groups_(n, 1) {\n iota(parents_.begin(), parents_.end(), 0);\n }\n \n int find(const int i) {\n if (i == parents_[i]) {\n return i;\n }\n \n parents_[i] = find(parents_[i]);\n return parents_[i];\n }\n \n bool do_union(const int i, const int j) {\n const int parent_i = find(i);\n const int parent_j = find(j);\n if (parent_i == parent_j) {\n return false;\n }\n \n const int final_group = groups_[parent_i] + groups_[parent_j];\n if (groups_[parent_i] <= groups_[parent_j]) {\n parents_[parent_i] = parent_j;\n groups_[parent_j] = final_group;\n groups_[parent_i] = 0;\n } else {\n parents_[parent_j] = parent_i;\n groups_[parent_i] = final_group;\n groups_[parent_j] = 0;\n }\n return true;\n }\n \n int group(const int i) {\n return groups_[find(i)];\n }\n \n private:\n vector<int> parents_;\n vector<int> groups_;\n };\n \n public:\n long long countPaths(const int n, vector<vector<int>> &edges) {\n bool is_prime[n];\n populate_is_prime(is_prime, n);\n \n vector<int> graph[n];\n DisjointSet ds(n);\n for (const vector<int> &edge : edges) {\n const int node1 = edge.front() - 1;\n const int node2 = edge.back() - 1;\n graph[node1].emplace_back(node2);\n graph[node2].emplace_back(node1);\n if (!is_prime[node1] && !is_prime[node2]) {\n ds.do_union(node1, node2);\n }\n }\n \n long long ret = 0LL;\n for (int node = 0; node < n; ++node) {\n if (!is_prime[node]) {\n continue;\n }\n int sum = 0;\n for (const int next : graph[node]) {\n if (is_prime[next]) {\n continue;\n }\n const int group = ds.group(next);\n ret += static_cast<long long>(sum + 1) * group;\n sum += group;\n }\n }\n return ret;\n }\n \n private:\n void populate_is_prime(bool *is_prime, const int n) {\n memset(is_prime, 0x01, sizeof(bool) * n);\n is_prime[0] = false;\n for (int i = 2; i < n + 1; ++i) {\n if (is_prime[i - 1]) {\n for (int j = i; j < n / i + 1; ++j) {\n is_prime[i * j - 1] = false;\n }\n }\n }\n }\n};\n```\n**4. Use the `Linear Sieve` (`Euler\'s Sieve`) Algorithm to get all prime numbers from `1` to `n`, and then use the Disjoint Set**\n```\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n */\nclass Solution {\n private:\n class DisjointSet {\n public:\n DisjointSet(const int n) : parents_(n), groups_(n, 1) {\n iota(parents_.begin(), parents_.end(), 0);\n }\n \n int find(const int i) {\n if (i == parents_[i]) {\n return i;\n }\n \n parents_[i] = find(parents_[i]);\n return parents_[i];\n }\n \n bool do_union(const int i, const int j) {\n const int parent_i = find(i);\n const int parent_j = find(j);\n if (parent_i == parent_j) {\n return false;\n }\n \n const int final_group = groups_[parent_i] + groups_[parent_j];\n if (groups_[parent_i] <= groups_[parent_j]) {\n parents_[parent_i] = parent_j;\n groups_[parent_j] = final_group;\n groups_[parent_i] = 0;\n } else {\n parents_[parent_j] = parent_i;\n groups_[parent_i] = final_group;\n groups_[parent_j] = 0;\n }\n return true;\n }\n \n int group(const int i) {\n return groups_[find(i)];\n }\n \n private:\n vector<int> parents_;\n vector<int> groups_;\n };\n \n public:\n long long countPaths(const int n, vector<vector<int>> &edges) {\n bool is_prime[n];\n populate_is_prime(is_prime, n);\n \n vector<int> graph[n];\n DisjointSet ds(n);\n for (const vector<int> &edge : edges) {\n const int node1 = edge.front() - 1;\n const int node2 = edge.back() - 1;\n graph[node1].emplace_back(node2);\n graph[node2].emplace_back(node1);\n if (!is_prime[node1] && !is_prime[node2]) {\n ds.do_union(node1, node2);\n }\n }\n \n long long ret = 0LL;\n for (int node = 0; node < n; ++node) {\n if (!is_prime[node]) {\n continue;\n }\n int sum = 0;\n for (const int next : graph[node]) {\n if (is_prime[next]) {\n continue;\n }\n const int group = ds.group(next);\n ret += static_cast<long long>(sum + 1) * group;\n sum += group;\n }\n }\n return ret;\n }\n \n private:\n void populate_is_prime(bool *is_prime, const int n) {\n memset(is_prime, 0x01, sizeof(bool) * n);\n vector<int> primes;\n is_prime[0] = false;\n for (int i = 2; i < n + 1; ++i) {\n if (is_prime[i - 1]) {\n primes.emplace_back(i);\n }\n for (const int p : primes) {\n if (p * i > n) {\n break;\n }\n is_prime[p * i - 1] = false;\n if (i % p == 0) {\n // `p` is the least prime factor of `i`\n break;\n }\n }\n }\n }\n};\n```
0
0
[]
0
count-valid-paths-in-a-tree
solution
solution-by-hemanth-123-ecoe
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
hemanth-123
NORMAL
2023-09-25T15:13:25.256438+00:00
2023-09-25T15:13:25.256465+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n def mul(x, y):\n return x * y\n \n def dfs(x, f, con, prime, r):\n v = [1 - prime[x], prime[x]]\n for y in con[x]:\n if y == f:\n continue\n p = dfs(y, x, con, prime, r)\n r[0] += mul(p[0], v[1]) + mul(p[1], v[0])\n if prime[x]:\n v[1] += p[0]\n else:\n v[0] += p[0]\n v[1] += p[1]\n return v\n \n prime = [True] * (n + 1)\n prime[1] = False\n \n all_primes = []\n for i in range(2, n + 1):\n if prime[i]:\n all_primes.append(i)\n for x in all_primes:\n temp = i * x\n if temp > n:\n break\n prime[temp] = False\n if i % x == 0:\n break\n \n con = [[] for _ in range(n + 1)]\n for e in edges:\n con[e[0]].append(e[1])\n con[e[1]].append(e[0])\n \n r = [0]\n dfs(1, 0, con, prime, r)\n return r[0]\n\n```
0
0
['Python3']
0
count-valid-paths-in-a-tree
Python 3 O(n*n^0.5)) solution
python-3-onn05-solution-by-vladislav_zav-oat9
\nclass Solution:\n def is_prime(self, num):\n if num == 1:\n return False\n for i in range(2, int(num ** (0.5)) + 1):\n
vladislav_zavadski
NORMAL
2023-09-25T10:19:07.336565+00:00
2023-09-25T10:19:07.336586+00:00
7
false
```\nclass Solution:\n def is_prime(self, num):\n if num == 1:\n return False\n for i in range(2, int(num ** (0.5)) + 1):\n if num % i == 0:\n return False\n return True\n \n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = defaultdict(set)\n \n for a,b in edges:\n graph[a].add(b)\n graph[b].add(a)\n \n self.ans = 0\n \n def traverse(node, parent = -1): \n is_prime = self.is_prime(node)\n zero_primes_paths_count = 0\n one_prime_paths_count = 0\n \n for nxt in graph[node]:\n if nxt != parent:\n z, o = traverse(nxt, node)\n if is_prime:\n self.ans += z * zero_primes_paths_count\n else:\n self.ans += z * one_prime_paths_count\n self.ans += o * zero_primes_paths_count\n zero_primes_paths_count += z\n one_prime_paths_count += o\n \n if not is_prime:\n self.ans += one_prime_paths_count\n else:\n self.ans += zero_primes_paths_count\n \n if is_prime:\n return (0, zero_primes_paths_count + 1)\n return (zero_primes_paths_count + 1, one_prime_paths_count)\n \n traverse(1)\n \n return self.ans\n```
0
0
['Math', 'Depth-First Search', 'Graph', 'Python']
0
count-valid-paths-in-a-tree
Solution using DFS+DP
solution-using-dfsdp-by-ksbu_2003-zu88
Intuition\n Describe your first thoughts on how to solve this problem. \ninitially i thought this can be solved by using DP approach\n# Approach\n Describe your
ksbu_2003
NORMAL
2023-09-25T08:32:48.962716+00:00
2023-09-25T08:32:48.962740+00:00
68
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ninitially i thought this can be solved by using DP approach\n# Approach\n<!-- Describe your approach to solving the problem. -->\nusing dfs we can find number of prime paths containing a single prime and number of non-prime paths for each node w.r.to thier children.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$ O(n+m) $$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$ O(n) $$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int>isprime;\n long long sulli=0;\n void check(int n)\n {\n isprime[0]=isprime[1]=0;\n for(int i=2;i<=n;i++)\n {\n for(int j=2*i;j<=n;j+=i)\n {\n isprime[j]=0;\n }\n }\n }\n pair<int,int> dfs(int node,int par,vector<int>graph[])\n {\n pair<int,int>v={!isprime[node],isprime[node]};\n for(auto &it:graph[node])\n {\n if(it==par) continue;\n auto p=dfs(it,node,graph);\n sulli+=(p.first*1LL*v.second+p.second*1LL*v.first);\n if(isprime[node]) v.second+=p.first;\n else {\n v.first+=p.first;\n v.second+=p.second;\n }\n }\n return v;\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<int>graph[n+1];\n isprime.resize(n+1,1);\n check(n);\n for(int i=0;i<edges.size();i++)\n {\n graph[edges[i][0]].push_back(edges[i][1]);\n graph[edges[i][1]].push_back(edges[i][0]);\n }\n dfs(1,-1,graph);\n return sulli;\n }\n};\n```
0
0
['Dynamic Programming', 'Tree', 'Depth-First Search', 'C++']
1
count-valid-paths-in-a-tree
Single DFS
single-dfs-by-raj_tirtha-2kwg
Code\n\nclass Solution {\npublic:\n long long ans=0;\n void dfs(int node,vector<vector<int>> &adj,int parent,vector<long long> &dp1,vector<long long> &dp2
raj_tirtha
NORMAL
2023-09-25T07:50:38.974954+00:00
2023-09-25T07:50:38.974972+00:00
5
false
# Code\n```\nclass Solution {\npublic:\n long long ans=0;\n void dfs(int node,vector<vector<int>> &adj,int parent,vector<long long> &dp1,vector<long long> &dp2,vector<bool> &isprime){\n long long cnt=0;\n long long temp=0;\n for(auto it:adj[node]){\n if(it==parent) continue;\n dfs(it,adj,node,dp1,dp2,isprime);\n if(isprime[node]==0){\n cnt+=dp1[it];\n if(isprime[it]){\n dp2[it]++;\n }\n temp+=dp2[it];\n }else{\n cnt+=dp1[it];\n temp+=dp1[it];\n }\n }\n dp2[node]=temp;\n long long temp1=0;\n for(auto it:adj[node]){\n if(it==parent) continue;\n if(isprime[node]==0){\n temp+=(cnt-dp1[it])*(dp2[it]);\n }else{\n temp1+=(cnt-dp1[it])*(dp1[it]);\n }\n }\n temp1/=2;\n if(isprime[node]==0) dp1[node]=cnt;\n if(isprime[node]==0) dp1[node]++;\n temp+=temp1;\n ans+=temp;\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<bool> isprime(n+1,1);\n isprime[1]=0;\n for(int i=2;i<=n;i++){\n if(isprime[i]){\n for(long long j=i*1LL*i;j<=n;j+=i){\n isprime[j]=0;\n }\n }\n }\n vector<vector<int>> adj(n+1);\n for(int i=0;i<edges.size();i++){\n int u=edges[i][0],v=edges[i][1];\n adj[u].push_back(v);\n adj[v].push_back(u);\n }\n vector<long long> dp1(n+1,0),dp2(n+1,0);\n dfs(1,adj,-1,dp1,dp2,isprime);\n return ans;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
C++ DFS & Seive Intutive
c-dfs-seive-intutive-by-vinayag29-dbet
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
vinayag29
NORMAL
2023-09-25T05:29:44.748977+00:00
2023-09-25T05:29:44.749001+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void seive(vector<bool> &primes, int n)\n {\n primes[0] = 0;\n primes[1] = 0;\n for(int i = 2 ; i <= sqrt(n) ; i++)\n {\n for(int j = i*i ; j < n ; j += i)\n {\n primes[j] = 0;\n }\n }\n }\n pair<long long, long long> dfs(int node, unordered_map<int, set<int>> &adj, vector<int> &vis, vector<bool> &primes, long long *ans)\n {\n vis[node] = 1;\n long long prime0 = 0; //prime0 -> total no. of path with 0 count of prime till now encountered\n long long prime1 = 0; //prime1 -> total no. of path with 1 count of prime till now encountered\n pair<long long, long long> x;\n for(auto it: adj[node])\n {\n if(!vis[it])\n {\n x = dfs(it, adj, vis, primes, ans);\n if(primes[node] == 1)\n {\n *ans = *ans + (prime0*x.first + x.first);\n prime0 = prime0 + x.first;\n }\n else\n {\n *ans = *ans + (prime1*x.first + prime0*x.second + x.second);\n prime0 = prime0 + x.first;\n prime1 = prime1 + x.second;\n }\n }\n }\n if(primes[node])\n return {0, prime0+1};\n else\n return {prime0+1, prime1};\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<bool> primes(n+1, 1); \n seive(primes, n+1);\n \n unordered_map<int, set<int>> adj;\n for(int i = 0 ; i < edges.size() ; i++)\n {\n adj[edges[i][0]].insert(edges[i][1]);\n adj[edges[i][1]].insert(edges[i][0]);\n }\n\n vector<int> vis(n+1, 0);\n\n long long ans = 0;\n dfs(1, adj, vis, primes, &ans);\n return ans;\n\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
Python - DP count with union find and dfs from primes
python-dp-count-with-union-find-and-dfs-33ogx
Intuition\nUse union find structure variation with counting.\nConnect only non prime nodes.\nThis way count of parent can give us count of non primes in compone
Ante_
NORMAL
2023-09-24T22:38:12.989358+00:00
2023-09-24T22:40:09.432295+00:00
33
false
# Intuition\nUse union find structure variation with counting.\nConnect only non prime nodes.\nThis way count of parent can give us count of non primes in component. This can be used later to do dfs from prime nodes and have something like memoization effect for that search.\nLater on just do dfs from prime nodes and calculate how many combinations of node pairs pass through that node.\n\nAlso made prime lookup table to speed up is prime check.\n\n# Complexity\n- Time complexity:\n$$O(n + n \\sqrt{n} + E)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass UF:\n def __init__(self, N) -> None:\n self.p, self.size = list(range(N)), [1] * N\n\n def find(self, x):\n if self.p[x] != x: self.p[x] = self.find(self.p[x])\n return self.p[x]\n\n def connected(self, x, y): return self.find(x) == self.find(y)\n \n def connect(self, x, y):\n px = self.find(self.p[x])\n py = self.find(self.p[y])\n\n if px != py:\n if self.size[px] >= self.size[py]:\n self.p[py] = self.p[px]\n self.size[px] += self.size[py]\n else:\n self.p[px] = self.p[py]\n self.size[py] += self.size[px]\n\n def get_size(self, x): return self.size[self.find(x)]\n\nclass Solution:\n def get_primes(self, n):\n primes = [True] * (n+1)\n primes[0] = primes[1] = False\n for i in range(2, n+1):\n if primes[i]:\n for j in range(i*i, n+1, i): primes[j] = False\n return primes\n\n def countPaths(self, n, edges) -> int:\n g = defaultdict(set)\n prime = self.get_primes(n)\n uf = UF(n + 1)\n for u, v in edges:\n g[u].add(v)\n g[v].add(u)\n if prime[u] or prime[v]: continue\n uf.connect(u, v)\n \n def count_nodes(node):\n count = 0\n for nei in g[node]:\n if not prime[nei]: count += uf.get_size(nei)\n return count\n\n result = 0\n\n for i in range(1, n + 1):\n if prime[i]:\n count_of_nodes = count_nodes(i)\n\n for nei in g[i]:\n if prime[nei]: continue\n result += uf.get_size(nei)\n count_of_nodes -= uf.get_size(nei)\n result += count_of_nodes * uf.get_size(nei) \n\n return result\n```
0
0
['Math', 'Depth-First Search', 'Union Find', 'Graph', 'Python', 'Python3']
0
count-valid-paths-in-a-tree
Python (Beats 12.5%)
python-beats-125-by-trentono-mt0k
\nfrom collections import defaultdict\n\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int: \n primes = self.fi
trentono
NORMAL
2023-09-24T20:40:04.544063+00:00
2023-09-24T20:40:04.544082+00:00
6
false
```\nfrom collections import defaultdict\n\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int: \n primes = self.find_primes(n)\n prime_neighbors = defaultdict(list)\n for a, b in edges:\n if a in primes and b not in primes:\n prime_neighbors[a].append(b)\n elif b in primes and a not in primes:\n prime_neighbors[b].append(a)\n\n uf = UnionFind(n)\n for a, b in edges:\n if a not in primes and b not in primes:\n uf.union(a, b)\n \n return sum(self.valid_through(p, prime_neighbors, uf) for p in primes)\n\n def find_primes(self, n):\n is_prime = [True]*(n+1)\n is_prime[0] = False\n is_prime[1] = False\n i = 2\n while i*i <= n:\n if not is_prime[i]:\n i += 1\n continue\n j = 2\n while j*i <= n:\n is_prime[j*i] = False\n j += 1\n \n i += 1\n \n return {i for i in range(n+1) if is_prime[i]}\n \n def valid_through(self, p, prime_neighbors, uf):\n vt = 0\n st_sum = sum(uf.size(a) for a in prime_neighbors[p])\n for a in prime_neighbors[p]:\n vt += uf.size(a)*(st_sum-uf.size(a))\n \n vt //= 2\n vt += st_sum\n \n return vt\n \n\nclass UnionFind:\n def __init__(self, n):\n self._table = {i: i for i in range(1, n+1)}\n self._size = {i: 1 for i in range(1, n+1)}\n\n def union(self, a, b):\n a_size = self.size(a)\n b_size = self.size(b)\n self._table[self.find(b)] = self.find(a)\n self._size[self.find(a)] = a_size + b_size\n\n def find(self, a):\n if a != self._table[a]:\n self._table[a] = self.find(self._table[a])\n\n return self._table[a]\n\n def size(self, i):\n return self._size[self.find(i)]\n \n```
0
0
['Python3']
0
count-valid-paths-in-a-tree
Tree Rerooting || clean & neat solution || Easy to understand
tree-rerooting-clean-neat-solution-easy-fn4qb
Intuition\n Describe your first thoughts on how to solve this problem. \nTree rerooting is all you need!\n\n# Approach\n Describe your approach to solving the p
Varan03
NORMAL
2023-09-24T20:28:02.405680+00:00
2023-09-24T20:29:15.026554+00:00
37
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTree rerooting is all you need!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Find all primes in the range [1,n]\n2. Root the tree at any node, let\'s say 1\n3. Run a dfs to calculate no of paths starting from node i to its subtree nodes which contains exactly 0 or 1 primes numbers, denote that as dp[i][0] and dp[i][1] respectively\n4. now use the above values and maintain parent contribution in the second dfs run and find answers for all the nodes (Refer to code)\n\n#### For those who are new to Tree Rerooting -\n\nProblem asks you to **find answer for all nodes in unrooted tree**, so in brute force one can run some function to calculate answer for all nodes but that would ultimately take `O(n^2)` as you call it for every node independently.\n\nIn smarter way, you can avoid duplicate calculations by tree rerooting\ntake this example\n![image.png](https://assets.leetcode.com/users/images/0778ba6d-ff31-45e2-942d-81d83bace0f8_1695586588.5081756.png)\n\nYou can root the tree at 1 and calculate dp from bottom.\nNow you need answer for node 2\nThen, you need to consider all answers from 1 (parent) except those from subtree starting at 2(current node). now how to eliminate the values contributed by 2 to its parent 1?\n\nyou need to think of this thing in second dfs2 to maintain parent contribution in every tree rerooting problem.\n\n\nIn short, \n`1. Root the tree at arbitary node`\n`2. Find answer for rooted node while calculating downward dp`\n`3. Then, think how to eliminate contribution of current node from its parents calculated values to find answers from subtree of parent (imp step)`\n`4. Use bottom dp and parent contribution for each node in single dfs to calculate answer for every node`\n\nGo through the below code and get the idea thoroughly. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`O(nloglogn + n + n)`\nsieve + dfs1 + dfs2 \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`O(n)`\nn -> no of nodes in the tree\n# Code\n```\n#define ll long long\nclass Solution {\npublic:\n void sieve(vector<bool> &isPrime, int n){\n isPrime[1] = false;\n for(int i=2; i<n; ++i){\n if(isPrime[i]){\n for(int j=2*i; j<n; j+=i){\n isPrime[j] = false;\n }\n }\n }\n }\n \n void dfs(int node, int par, vector<int> G[], vector<pair<ll,ll>> &paths, vector<bool> &isPrime){\n \n ll one = 0, zero = 0;\n \n for(auto &child: G[node]){\n if(child==par) continue;\n dfs(child,node,G,paths,isPrime);\n one+=paths[child].second;\n zero+=paths[child].first;\n }\n \n if(isPrime[node]){\n paths[node] = {0ll,1+zero};\n }\n else paths[node] = {1+zero,one};\n }\n \n void dfs2(int node, int par, pair<ll,ll> par_contri, vector<int> G[], vector<pair<ll,ll>> &paths, vector<bool> &isPrime, ll &ans){\n \n ans += paths[node].second; // from bottom\n if(isPrime[node]){\n ans += par_contri.first;\n }\n else ans += par_contri.second;\n \n for(auto &child: G[node]){\n if(child==par) continue;\n ll ones = 0, zero = 0;\n if(isPrime[node]){\n ones = paths[node].second-paths[child].first;\n // from par_contri\n ones += par_contri.first;\n }\n else{ \n ones = paths[node].second - paths[child].second;\n zero = paths[node].first - paths[child].first;\n \n zero += par_contri.first;\n ones += par_contri.second;\n }\n \n dfs2(child,node,{zero,ones},G,paths,isPrime,ans);\n }\n \n }\n \n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<bool> isPrime(n+5,true);\n sieve(isPrime,n+5);\n \n vector<int> G[n+5];\n for(auto &x: edges){\n int a = x[0], b = x[1];\n G[a].push_back(b);\n G[b].push_back(a);\n }\n \n vector<pair<ll,ll>> paths(n+5,{0,0}); // {0,1} prime count paths\n dfs(1,-1,G,paths,isPrime);\n ll ans = 0;\n dfs2(1,-1,{0,0},G,paths,isPrime,ans);\n int cnt_primes = 0;\n for(int i=1; i<=n; ++i){\n cnt_primes+=(isPrime[i]);\n }\n ans-=cnt_primes;\n return ans/2;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
DSU Solution || Beats 100%
dsu-solution-beats-100-by-hacker_antace-d4tr
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
hacker_antace
NORMAL
2023-09-24T17:07:53.802445+00:00
2023-09-24T17:07:53.802470+00:00
19
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass DSU{\n public:\n vector<int> rank, size, parent;\n DSU(int n){\n rank.resize(n+1, 0);\n parent.resize(n+1);\n size.resize(n+1, 1);\n for(int i = 1; i<=n; i++) parent[i] = i;\n }\n int find_parent(int u){\n if(u == parent[u]) return u;\n return parent[u] = find_parent(parent[u]);\n }\n void unionfind(int u, int v){\n int pu = find_parent(u);\n int pv = find_parent(v);\n if(pu == pv) return;\n if(rank[pu] < rank[pv]){\n parent[pu] = pv;\n rank[pv]++;\n size[pv] += size[pu]; \n }\n else if(rank[pu] > rank[pv]){\n parent[pv] = pu;\n rank[pu]++;\n size[pu] += size[pv];\n }\n else{\n parent[pu] = pv;\n rank[pv]++;\n size[pv] += size[pu];\n }\n }\n};\nclass Solution {\npublic:\n vector<int> sieveOfEratosthenes(int limit) {\n vector<int> prime;\n vector<bool> isPrime(limit + 1, true);\n isPrime[0] = isPrime[1] = false;\n for (int p = 2; p * p <= limit; p++) {\n if (isPrime[p]) {\n for (int i = p * p; i <= limit; i += p) {\n isPrime[i] = false;\n }\n }\n }\n for (int i = 2; i <= limit; i++) {\n if (isPrime[i]) {\n prime.push_back(i);\n }\n }\n return prime;\n }\n\n long long countPaths(int n, vector<vector<int>>& edges) {\n \n vector<vector<int>> g(n + 1);\n for (auto &e : edges) {\n g[e[0]].push_back(e[1]);\n g[e[1]].push_back(e[0]);\n }\n\n vector<int> prime = sieveOfEratosthenes(n);\n unordered_map<int, int> pmp;\n for(auto i:prime) pmp[i]++;\n DSU ds(n);\n for(int i = 0; i<edges.size(); i++){\n if(pmp.find(edges[i][0])==pmp.end()&&pmp.find(edges[i][1])==pmp.end()){\n ds.unionfind(edges[i][0], edges[i][1]);\n }\n }\n long long ans = 0;\n for(auto i:pmp){\n long long sum = 0;\n // count the number of nodes that are connected to a particular prime number \n for(int v : g[i.first]){\n if(pmp.find(v) == pmp.end()){\n sum += ds.size[ds.find_parent(v)];\n }\n }\n // finding paths from a particular component \n // one is added to consider the prime number itself\n // subtraction of k is due to the elimination of duplicates\n long long curr = 0;\n for(int v : g[i.first]){\n if(pmp.find(v) == pmp.end()){\n long long k = ds.size[ds.find_parent(v)]; \n curr += k*(sum + 1 - k);\n sum -= k;\n }\n }\n ans += curr;\n }\n return ans;\n }\n};\n```
0
0
['Union Find', 'Graph', 'C++']
0
count-valid-paths-in-a-tree
100/100 Beats
100100-beats-by-ranilmukesh-9oeg
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ranilmukesh
NORMAL
2023-09-24T16:06:03.506301+00:00
2023-09-24T16:06:03.506334+00:00
26
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n boolean[] isPrime;\n List<Integer>[] treeEdges;\n long r;\n \n boolean[] preparePrime(int n) {\n // Sieve of Eratosthenes <3 \n boolean[] isPrime = new boolean[n+1];\n long paths = 0;\n for (int i = 2; i < n+1; i++) { isPrime[i] = true; }\n for (int i = 2; i <= n/2; i++) {\n for (int j = 2*i; j < n + 1; j += i) { isPrime[j] = false; }\n }\n return isPrime;\n }\n\n List<Integer>[] prepareTree(int n, int[][] edges) {\n List<Integer>[] treeEdges = new List[n+1];\n for (int i = 0; i < edges.length; i++) {\n int[] edge = edges[i];\n if (treeEdges[edge[0]] == null) {\n treeEdges[edge[0]] = new ArrayList<Integer>();\n }\n treeEdges[edge[0]].add(edge[1]);\n if (treeEdges[edge[1]] == null) {\n treeEdges[edge[1]] = new ArrayList<Integer>();\n }\n treeEdges[edge[1]].add(edge[0]);\n }\n return treeEdges;\n }\n\n // returns [nbPathsWithOnePrimeNode, nbPathsWithNoPrimeNode] in path so far\n public long[] countPathDfs(int node, int parent) {\n long[] v = new long[]{isPrime[node] ? 0 : 1, isPrime[node] ? 1 : 0};\n\n List<Integer> edges = treeEdges[node];\n if (edges == null) { // in the case cases, happens with n = 1, edges = []\n return v;\n }\n \n for (Integer neigh: edges) {\n if (neigh == parent) { continue; }\n long[] ce = countPathDfs(neigh, node);\n r += v[0] * ce[1] + v[1] * ce[0];\n if (isPrime[node]) {\n v[1] += ce[0];\n } else {\n v[0] += ce[0];\n v[1] += ce[1];\n\n }\n }\n return v;\n }\n \n public long countPaths(int n, int[][] edges) {\n isPrime = preparePrime(n);\n treeEdges = prepareTree(n, edges);\n \n r = 0;\n countPathDfs(1, 0);\n return r;\n }\n}\n```
0
0
['Java']
0
count-valid-paths-in-a-tree
Sieve of Eratosthenes + DFS with kinda DSU O(n) clean code
sieve-of-eratosthenes-dfs-with-kinda-dsu-w0q2
\n using ll = long long;\n ll countPaths(int n, vector<vector<int>>& edges) {\n const auto getPrimes = [](int n) {\n vector<int> values(
dmitrii_bokovikov
NORMAL
2023-09-24T14:36:08.158578+00:00
2023-09-24T19:39:00.631414+00:00
14
false
```\n using ll = long long;\n ll countPaths(int n, vector<vector<int>>& edges) {\n const auto getPrimes = [](int n) {\n vector<int> values(n + 1);\n iota(begin(values) + 2, end(values), 2);\n for (int i = 2; i <= n; i++) {\n if (values[i] == 0) {\n continue;\n }\n for (int j = i * 2; j <= n; j += i) {\n values[j] = 0;\n }\n }\n return values;\n };\n const auto primes = getPrimes(n);\n\n vector<vector<int>> g(n);\n for (int i = 0; i < size(edges); ++i) {\n g[edges[i][0] - 1].push_back(edges[i][1] - 1);\n g[edges[i][1] - 1].push_back(edges[i][0] - 1);\n }\n \n vector<int> componentSizes;\n vector<int> valToComponentIdx(n, -1);\n function<int(int, int)> dfs;\n dfs = [&](int v, int p) {\n valToComponentIdx[v] = size(componentSizes);\n int res = 1;\n for (const auto to: g[v]) {\n if (to != p && !primes[to + 1]) {\n res += dfs(to, v);\n }\n }\n return res;\n };\n for (int i = 0; i < n; ++i) {\n if (valToComponentIdx[i] == -1 && !primes[i + 1]) {\n componentSizes.push_back(dfs(i, -1));\n }\n }\n ll ans = 0;\n for (int i = 0; i < n; ++i) {\n if (primes[i + 1]) {\n ll c = 0;\n for (const auto to: g[i]) {\n if (valToComponentIdx[to] != -1) {\n ans += componentSizes[valToComponentIdx[to]] * (c + 1);\n c += componentSizes[valToComponentIdx[to]];\n }\n }\n }\n }\n return ans;\n }\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
Good Question.
good-question-by-shyamprajapati2672-cs3p
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
shyamprajapati2672
NORMAL
2023-09-24T12:34:41.839454+00:00
2023-09-24T12:34:41.839484+00:00
44
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\n\nint fck=0;\n int isprime[100000+1];\n void precompute(){\n // cout<<fck<<endl;\n for(int i=0;i<=1e5;i++)isprime[i]=1;\n isprime[0]=0;\n isprime[1]=0;\n for(int i=2;i*i<=1e5;i++){\n int x=i*i;\n while(x<=1e5){\n isprime[x]=0;\n x+=i;\n }\n }\n }\n\nclass Solution {\npublic:\n int path;\n // int N=1e5+1;/\n // map<int,int> mp;\n // map<int,int> p;\nvector<int> mp,p; \n int dfs(int u,int par,vector<vector<int>> &adj,int path){\n if(isprime[u])return 0;\n p[u]=path;\n int f=1;\n for(auto it:adj[u]){\n if(it!=par){\n f+=dfs(it,u,adj,path);\n }\n }\n \n return f;\n }\n \n long long countPaths(int n, vector<vector<int>>& edges) {\n if(fck==0)\n precompute();\n fck++;\n mp.clear();\n p.clear();\n mp.resize(2*n+1,0);\n p.resize(2*n+1,0);\n path=1;\n vector<vector<int>> adj(n+1);\n for(auto it:edges){\n adj[it[0]].push_back(it[1]);\n adj[it[1]].push_back(it[0]);\n }\n long long ans=0;\n for(int i=1;i<=n;i++){\n if(isprime[i]){\n int sx=0;\n \n // int n=0,m=0;\n vector<int> v;\n for(auto it:adj[i]){\n int x;\n if(p[it])x=mp[p[it]];\n else{\n \n x=dfs(it,i,adj,path);\n mp[path]=x;\n path++;\n }\n \n \n v.push_back(x);\n }\n // cout<<i<<" "<<n<<" "<<m<<endl;\n// for(auto it:v)cout<<it<<" ";\n// cout<<endl;\n \n long long sums=0;\n long long sum=0;\n \n \n \n for(auto it:v){\n sums+=1ll*it*it;\n sum+=it;\n }\n ans+=sum+(sum*sum-sums)/2ll;\n\n // cout<<ans<<endl;\n // ans+=(n+1)*(m+1)-1;\n \n }\n \n }\n \n return ans;\n \n }\n};\n```
0
0
['Math', 'Dynamic Programming', 'Depth-First Search', 'C++']
0
count-valid-paths-in-a-tree
Java 29ms faster than 100% DFS
java-29ms-faster-than-100-dfs-by-sedak82-9v7z
Code\n\nclass Solution {\n boolean[] isPrime;\n List<Integer>[] treeEdges;\n long r;\n \n boolean[] preparePrime(int n) {\n // Sieve of Er
sedak82
NORMAL
2023-09-24T12:28:06.909819+00:00
2023-09-24T12:28:06.909839+00:00
24
false
# Code\n```\nclass Solution {\n boolean[] isPrime;\n List<Integer>[] treeEdges;\n long r;\n \n boolean[] preparePrime(int n) {\n // Sieve of Eratosthenes <3 \n boolean[] isPrime = new boolean[n+1];\n long paths = 0;\n for (int i = 2; i < n+1; i++) { isPrime[i] = true; }\n for (int i = 2; i <= n/2; i++) {\n for (int j = 2*i; j < n + 1; j += i) { isPrime[j] = false; }\n }\n return isPrime;\n }\n\n List<Integer>[] prepareTree(int n, int[][] edges) {\n List<Integer>[] treeEdges = new List[n+1];\n for (int i = 0; i < edges.length; i++) {\n int[] edge = edges[i];\n if (treeEdges[edge[0]] == null) {\n treeEdges[edge[0]] = new ArrayList<Integer>();\n }\n treeEdges[edge[0]].add(edge[1]);\n if (treeEdges[edge[1]] == null) {\n treeEdges[edge[1]] = new ArrayList<Integer>();\n }\n treeEdges[edge[1]].add(edge[0]);\n }\n return treeEdges;\n }\n\n // returns [nbPathsWithOnePrimeNode, nbPathsWithNoPrimeNode] in path so far\n public long[] countPathDfs(int node, int parent) {\n long[] v = new long[]{isPrime[node] ? 0 : 1, isPrime[node] ? 1 : 0};\n\n List<Integer> edges = treeEdges[node];\n if (edges == null) { // in the case cases, happens with n = 1, edges = []\n return v;\n }\n \n for (Integer neigh: edges) {\n if (neigh == parent) { continue; }\n long[] ce = countPathDfs(neigh, node);\n r += v[0] * ce[1] + v[1] * ce[0];\n if (isPrime[node]) {\n v[1] += ce[0];\n } else {\n v[0] += ce[0];\n v[1] += ce[1];\n\n }\n }\n return v;\n }\n \n public long countPaths(int n, int[][] edges) {\n isPrime = preparePrime(n);\n treeEdges = prepareTree(n, edges);\n \n r = 0;\n countPathDfs(1, 0);\n return r;\n }\n}\n```
0
0
['Java']
0
count-valid-paths-in-a-tree
Disjoint set Data structure , Union By Size ! ! ! ! ! ! ! !
disjoint-set-data-structure-union-by-siz-47mz
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Vedant_Rathore
NORMAL
2023-09-24T10:10:00.276529+00:00
2023-09-24T10:10:00.276550+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n//disjoint set datastructure !! \n#include<bits/stdc++.h>\nusing namespace std ;\n#define ll long long \n\nconst int N = 1e5+1 ;\nvector<bool>arr(N,0) ;\n\n\nvoid sieve_with_variation(){\n \n arr[0] = true;\n arr[1] = true; \n \n for( int i = 2 ; i <= N ; i++ ){\n \n if( arr[i]== false ){\n \n for( int j = (i<<1) ; j <= N ; j = j + i )\n {\n arr[j] = true ; \n \n }\n \n }\n \n }\n \n}\n\n\n\nclass DisjointSet{\n vector<int>rank , parent , size ;\n public : \n DisjointSet( int n ){\n // n is the no of vertices \n rank.resize(n+1,0) ;\n parent.resize(n+1) ;\nsize.resize(n+1) ;\n for( ll i = 0 ; i <= n ; i++ ) {parent[i] = i ; size[i] = 1 ;}\n }\n \n // member functions \n int FindParent( int u ){\n if( u == parent[u]) return u ;\n return parent[u] = FindParent( parent[u]) ;\n }\n \n void UnionByRank( int u , int v ){\n int pu = FindParent(u) ;\n int pv = FindParent(v) ;\n if( pu == pv ) return ;\n if( rank[pv] == rank[pu] ){\n parent[pv] = pu ; // v gets attached to u \n rank[u] += 1 ;\n }else if( rank[pv] < rank[pu]){\n parent[pv] = pu ;\n }else{\n parent[pu] = pv ;\n }\n return ; \n }\nvoid unionBySize(int u, int v) {\n int ulp_u = FindParent(u); \n int ulp_v = FindParent(v); \n if(ulp_u == ulp_v) return; \n if(size[ulp_u] < size[ulp_v]) {\n parent[ulp_u] = ulp_v; \n size[ulp_v] += size[ulp_u]; \n }\n else {\n parent[ulp_v] = ulp_u;\n size[ulp_u] += size[ulp_v]; \n }\n }\n \n void dfs( int vertex , vector<int>*adj , vector<int>&tmp) {\n \n for( auto child : adj[vertex]) {\n if( arr[child] == false ) continue ;\n int uP = FindParent(child) ;\n int getsz = size[uP] ;\n tmp.push_back(getsz) ;\n }\n }\n \n} ;\n\n\n\n\n\nclass Solution {\npublic:\n \n ll countPaths(int n, vector<vector<int>>& edges) {\n sieve_with_variation() ;\n DisjointSet ds(n+1) ;\n vector<int>adj[n+1] ;\n vector<int>primes ;\n unordered_map<int,bool>included ;\n for( int i = 0 ; i < edges.size() ; i++ ){\n int u , v ;\n u = edges[i][0] ;\n v = edges[i][1] ;\n adj[u].push_back(v) ;\n adj[v].push_back(u) ;\n if( arr[u] == false and included[u] == false ){\n included[u] = true ;\n primes.push_back(u) ;\n }\n if( arr[v] == false and included[v] == false ){\n included[v] = true ;\n primes.push_back(v) ;\n }\n if( arr[u] == false || arr[v] == false ) continue ;\n ds.unionBySize(u,v) ;\n }\n ll ans = 0 ;\n for( auto i : primes ){\n // cout <<"hello\\n" ;\n vector<int>tmp ;\n ds.dfs( i , adj , tmp ) ;\n \n ll sum = 0 ;\n for( auto it : tmp ){\n \n sum += it ;\n }\n \n ll s = 0 ;\n for( auto it : tmp ){\n s += it ;\n ans += it * ( sum - s ) ;\n }\n ans += sum ; \n }\n return ans ; \n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
Extremely long C++ solution | DP on Trees
extremely-long-c-solution-dp-on-trees-by-r26s
Intuition\n Describe your first thoughts on how to solve this problem. \nWhen answer for current node is dependent on some answer from its child nodes and paren
biswajit_kaushik
NORMAL
2023-09-24T09:45:06.182603+00:00
2023-09-24T09:45:06.182623+00:00
20
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen answer for current node is dependent on some answer from its child nodes and parent node, then DP on trees can be used to solve such type of problems.\n\nNote that my solution calculates the path for each node $$a$$ to node $$b$$ in its children as well as parent, then divides the answer by $$2$$ to remove repeated count for paths $$(a, b)$$ and $$(b, a)$$. \n\nHowever, we could simply find paths for a node in its children which would only count path $$(a, b)$$ once, and that is what we want. \nI missed this thought because of which my solution became extremely long.\n\n\n# Complexity\n- Time complexity: $$O(n) + O(n*log(logn))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n typedef long long llint;\n vector<vector<int>> adj;\n \n vector<llint> no_prime_child, no_prime_whole, one_prime_child, one_prime_whole, is_prime, par;\n \n void init(int n) {\n n += 10;\n adj.resize(n);\n no_prime_child.resize(n, -1);\n no_prime_whole.resize(n, -1);\n one_prime_child.resize(n, -1);\n one_prime_whole.resize(n, -1);\n is_prime.resize(n + 1, -1);\n par.resize(n);\n }\n\n void seieve() {\n int N = is_prime.size() - 1;\n for(int i = 2; i * 1LL * i <= N; i++)\n if(is_prime[i] == -1)\n for(int j = i * 1LL * i; j <= N; j += i)\n if(is_prime[j] == -1)\n is_prime[j] = 0;\n \n is_prime[1] = 0;\n for(int i = 2; i <= N; i++)\n if(is_prime[i] == -1)\n is_prime[i] = 1;\n \n }\n \n void set_parent(int x) {\n for(auto& c: adj[x])\n if(c != par[x])\n {\n par[c] = x;\n set_parent(c);\n }\n // cout << "hfg" << par[6];\n }\n \n void set_no_prime_child(int x) {\n if(no_prime_child[x] != -1)\n return;\n no_prime_child[x] = 0;\n if(is_prime[x])\n {\n no_prime_child[x] = 0;\n return;\n }\n \n int p = par[x];\n for(auto& c: adj[x])\n if(c != p)\n {\n set_no_prime_child(c);\n no_prime_child[x] += no_prime_child[c];\n }\n no_prime_child[x]++;\n }\n \n void set_no_prime_whole(int x) {\n if(no_prime_whole[x] != -1)\n return;\n no_prime_whole[x] = 0;\n if(is_prime[x])\n {\n no_prime_whole[x] = 0;\n return;\n }\n \n int p = par[x];\n \n if(p == -1 || is_prime[p])\n {\n set_no_prime_child(x);\n no_prime_whole[x] = no_prime_child[x];\n }\n else\n {\n set_no_prime_whole(p);\n no_prime_whole[x] = no_prime_whole[p];\n }\n \n }\n \n void set_one_prime_child(int x) {\n if(one_prime_child[x] != -1)\n return;\n one_prime_child[x] = 0;\n if(is_prime[x])\n {\n for(auto& c: adj[x])\n if(c != par[x])\n {\n set_no_prime_child(c);\n one_prime_child[x] += no_prime_child[c];\n }\n one_prime_child[x]++;\n return;\n }\n for(auto& c: adj[x])\n if(c != par[x])\n {\n set_one_prime_child(c);\n one_prime_child[x] += one_prime_child[c];\n }\n }\n \n void set_one_prime_whole(int x) {\n if(one_prime_whole[x] != -1)\n return;\n one_prime_whole[x] = 0;\n if(is_prime[x])\n {\n set_one_prime_child(x);\n set_no_prime_whole(par[x]);\n one_prime_whole[x] = one_prime_child[x] + no_prime_whole[par[x]];\n return;\n }\n set_one_prime_whole(par[x]);\n if(is_prime[par[x]])\n {\n set_no_prime_child(x);\n set_one_prime_child(x);\n one_prime_whole[x] = one_prime_whole[par[x]] - no_prime_child[x] + one_prime_child[x];\n return;\n }\n one_prime_whole[x] = one_prime_whole[par[x]];\n }\n \n long long countPaths(int n, vector<vector<int>>& edges) {\n \n init(n);\n seieve();\n \n for(auto& e: edges)\n adj[e[0]].push_back(e[1]), adj[e[1]].push_back(e[0]);\n \n par[1] = -1;\n set_parent(1);\n // set one prime whole of root equal to child so that it is never called\n \n set_one_prime_child(1);\n one_prime_whole[1] = one_prime_child[1];\n llint ans = one_prime_whole[1];\n\n for(int i = 2; i <= n; i++)\n {\n set_one_prime_whole(i);\n ans += one_prime_whole[i];\n \n if(is_prime[i])\n ans--;\n }\n \n ans /= 2;\n return ans;\n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
C++ || Dp on Trees in Dp
c-dp-on-trees-in-dp-by-12345556-jdrk
Intuition\n Describe your first thoughts on how to solve this problem. \nmaintain 2 vales for every node in1 is for non prime paths starting in2 for prime paths
12345556
NORMAL
2023-09-24T09:42:58.702541+00:00
2023-09-24T09:42:58.702561+00:00
34
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nmaintain 2 vales for every node in1 is for non prime paths starting in2 for prime paths starting from that node.\n\nso for if the node is prime value we need to take the non-prime paths of the childrean and non prime paths is zero.\n\nif the node is non prime we can add all the prime paths to prime and non prime to non prime,\nthe above is upto maintaing the states of the every node\n\n\nhere is a simple maths formulation from that if the node is non-prime than we can ith child prime path with all other non prime paths formulation it we will get forumla\n\nval+=(in2[i])*(in1[s]-in1[i]);\nsimilary for prime nodes by formulation\nval+=(sum-in1[i])*in1[i];\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\n#define ll long long int\nclass Solution {\npublic:\n ll in1[100005];\n ll in2[100005];\n bool prime[100010];\n ll res;\n bool isprime(int n){\n if(n<2){\n return 0;\n }\n for(int i=2;i*i<=n;i++){\n if(n%i==0) return 0;\n }\n return 1;\n }\n\n ll dfs(int s,vector<vector<int>> &g,int par){\n ll ans=0;\n for(auto i:g[s]){\n if(i!=par){\n ans+=dfs(i,g,s);\n }\n }\n if(isprime(s+1)){\n in2[s]=1;\n in1[s]=0;\n ll sum=0;\n for(auto i:g[s]){\n if(i!=par){\n in2[s]+=in1[i];\n sum+=in1[i];\n }\n }\n ll val=0;\n for(auto i:g[s]){\n if(i!=par){\n val+=(sum-in1[i])*in1[i];\n }\n }\n ans+=val/2;\n ans+=in2[s]-1;\n }\n else{\n in1[s]=1;\n in2[s]=0;\n for(auto i:g[s]){\n if(i!=par){\n in1[s]+=in1[i];\n in2[s]+=in2[i];\n }\n }\n ll val=0;\n for(auto i:g[s]){\n if(i!=par){\n val+=(in2[i])*(in1[s]-in1[i]);\n // val+=(in2[i]);\n cout<<val<<\' \'<<i<<endl;\n }\n }\n cout<<val<<\' \';\n ans+=val;\n }\n \n res+=ans;\n cout<<ans<<\' \'<<s<<endl;\n return ans;\n }\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<vector<int>> g(n);\n \n memset(prime, true, sizeof(prime));\n prime[1]=false;\n prime[0]=false;\n \n \n for(auto i:edges){\n int u=i[0];\n int v=i[1];\n u--;\n v--;\n g[u].push_back(v);\n g[v].push_back(u);\n }\n res=0;\n // ll kk=dfs(0,g,-1)/2;\n return dfs(0,g,-1);\n \n }\n};\n```
0
0
['C++']
0
count-valid-paths-in-a-tree
SIEVE + DSU Approach EASY O(n), fast and memory efficient beats 100%
sieve-dsu-approach-easy-on-fast-and-memo-notl
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n 1. SIEve for finding all the primes till n, The complexity for this func
rahul19191
NORMAL
2023-09-24T08:29:43.564463+00:00
2023-09-24T08:29:43.564480+00:00
29
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n 1. SIEve for finding all the primes till $$n$$, The complexity for this function is $$O(sqrt(n))$$. \n 2. Now implemented DSU class with unionbySize method, The complexity of each function inside the class is $$O(4*\u03B1)$$. \n 3. Now we made a graph and added edges to both graph and dsu, while in dsu we will not be adding prime edges , therefore we will be having multiple components in the dsu.\n 4. Now for each prime node we will be find the answer as the total number of nodes we encountered till now multiplied by now of nodes in each neighbour node(which can be calculated by dsu).\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n\n# Code\n```\nclass Solution {\npublic:\n \n vector<int> graph[100005];\n bool vis[100005];\n \n int a[100005][2];\n \n void add(int x,int y){\n graph[x].push_back(y);\n graph[y].push_back(x);\n }\n \n unordered_map<int,int> sieve(int n){\n \n int b[n+1];\n memset(b,1,sizeof(b));\n \n for(int i = 2;i*i<=n;i++){\n \n if(b[i]){\n for(int j = i+i;j<=n;j+=i){\n b[j]=0;\n }\n }\n }\n \n unordered_map<int,int> prime;\n for(int i =2;i<=n;i++){\n if(b[i]){\n prime[i]++;\n }\n }\n \n return prime;\n \n } \n \n class dsu{\n vector<int> parent ,size;\n\n public: \n\n dsu(int n){\n parent.resize(n+1);\n size.resize(n+1);\n for(int i =0;i<=n;i++){\n parent[i]=i;\n size[i]=1;\n }\n }\n \n int findParent(int u){\n if(u==parent[u])\n return u;\n return u = findParent(parent[u]);\n }\n\n void sizeUnion(int u,int v){\n int pu = findParent(u);\n int pv = findParent(v);\n\n if(pu==pv) return;\n \n if(size[pu]<size[pv]){\n parent[pu] = pv;\n size[pv]+=size[pu];\n }else{\n parent[pv] = pu;\n size[pu]+=size[pv];\n }\n }\n\n int getSize(int u){\n int pu = findParent(u);\n return size[pu];\n }\n };\n\n\n long long countPaths(int n, vector<vector<int>>& edges) {\n for(int i =0;i<n+5;i++){\n vis[i]=false;\n graph[i].clear();\n a[i][0]=0;\n a[i][1]=0;\n }\n \n unordered_map<int,int> prime = sieve(n);\n\n dsu d(n);\n \n vector<int> graph[n+1];\n\n for(auto x : edges){\n int u = x[0];\n int v = x[1];\n graph[u].push_back(v);\n graph[v].push_back(u);\n if(prime[u] || prime[v]) continue;\n d.sizeUnion(u,v);\n }\n\n long long ans = 0;\n \n for(int i =1;i<=n;i++){\n if(!prime[i]) continue;\n long long total =1;\n for(int j =0;j<graph[i].size();j++){\n int u = graph[i][j];\n if(prime[u]) continue;\n long long nodes=d.getSize(u);\n ans = (ans + (total * nodes));\n total+=nodes;\n }\n }\n return ans;\n }\n};\n```
0
0
['Union Find', 'Graph', 'C++']
0
count-valid-paths-in-a-tree
Used Disjoint Set Union || Beats 87.5% in runtime and 100% memory usage
used-disjoint-set-union-beats-875-in-run-f7e1
\n# Approach\nJoin edges containing only composite number keeping track of sizes of each connected component.\nEdges containg two prime number are of no use.\nI
kb_00
NORMAL
2023-09-24T07:36:59.547281+00:00
2023-09-24T07:36:59.547300+00:00
18
false
\n# Approach\nJoin edges containing only composite number keeping track of sizes of each connected component.\nEdges containg two prime number are of no use.\nInsert the edges with only one prime and update the ans.\n\n**Tag me for more clarification.**\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n# Code\n```\nvector<int> prime;\nstruct dsu{\n vector<int> lvl;\n vector<int> par;\n vector<int> size;\n dsu(int n){\n lvl.assign(n+1,0);\n par.resize(n+1);\n iota(par.begin(),par.end(),0);\n size.assign(n+1,1);\n }\n int get(int i){\n if(i==par[i]) return i;\n return get(par[i]);\n }\n void unite(int a, int b){\n a = get(a);\n b = get(b);\n if(a==b) return;\n if(lvl[a]<lvl[b]) swap(a,b);\n par[b]=a;\n size[a]+=size[b];\n if(lvl[b]==lvl[a]) lvl[a]++;\n return;\n }\n long long count(int a, int b){\n if(!prime[a]) swap(a,b);\n b=get(b);\n long long ans = (long long)size[a]*(long long)size[b];\n size[a] += size[b];\n return ans;\n }\n};\nclass Solution {\npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n prime.assign(n+1,1);\n prime[0]=0;\n prime[1]=0;\n for(int i=2; i<=n; i++){\n if(prime[i]){\n for(int j=2*i; j<=n; j+=i) prime[j]=0;\n }\n }\n vector<vector<int>> st;\n dsu graph(n);\n for(auto u:edges){\n if(prime[u[0]] && prime[u[1]]) continue;\n if(prime[u[0]] || prime[u[1]]) {st.push_back(u); continue;}\n graph.unite(u[0],u[1]);\n }\n long long ans = 0;\n for(auto u:st){\n // cout<<u[0]<<u[1]<<endl;\n ans += graph.count(u[0],u[1]);\n }\n return ans;\n \n }\n};\n```
0
0
['Union Find', 'C++']
0
valid-boomerang
[Java/C++/Python] Straight Forward
javacpython-straight-forward-by-lee215-3h33
Assuming three points are A, B, C.\n\nThe first idea is that, calculate the area of ABC.\nWe can reuse the conclusion and prove in 812. Largest Triangle Area\n\
lee215
NORMAL
2019-05-05T04:09:20.857739+00:00
2019-05-05T04:28:05.121602+00:00
12,222
false
Assuming three points are A, B, C.\n\nThe first idea is that, calculate the area of ABC.\nWe can reuse the conclusion and prove in [812. Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area/discuss/122711/C++JavaPython-Solution-with-Explanation-and-Prove)\n\nThe other idea is to calculate the slope of AB and AC.\n`K_AB = (p[0][0] - p[1][0]) / (p[0][1] - p[1][1])`\n`K_AC = (p[0][0] - p[2][0]) / (p[0][1] - p[2][1])`\n\nWe check if `K_AB != K_AC`, instead of calculate a fraction.\n\nTime `O(1)` Space `O(1)`\n\n<br>\n\n**Java:**\n```\n public boolean isBoomerang(int[][] p) {\n return (p[0][0] - p[1][0]) * (p[0][1] - p[2][1]) != (p[0][0] - p[2][0]) * (p[0][1] - p[1][1]);\n }\n```\n\n**C++:**\n```\n bool isBoomerang(vector<vector<int>>& p) {\n return (p[0][0] - p[1][0]) * (p[0][1] - p[2][1]) != (p[0][0] - p[2][0]) * (p[0][1] - p[1][1]);\n }\n```\n\n**Python:**\n```\n def isBoomerang(self, p):\n return (p[0][0] - p[1][0]) * (p[0][1] - p[2][1]) != (p[0][0] - p[2][0]) * (p[0][1] - p[1][1])\n```\n
123
4
[]
9
valid-boomerang
C++ 1-liner: Triangle Area
c-1-liner-triangle-area-by-votrubac-qy0v
Intuition\nIn other words, we need to return true if the triangle area is not zero.\n\nFor the detailed explanation, see the comment by EOAndersson below.\n# So
votrubac
NORMAL
2019-05-05T04:01:16.062852+00:00
2019-05-06T07:01:49.218353+00:00
5,353
false
# Intuition\nIn other words, we need to return true if the triangle area is not zero.\n\nFor the detailed explanation, see the comment by [EOAndersson](https://leetcode.com/eoandersson/) below.\n# Solution\nCalculate the area of the triangle: ```x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)``` and compare it to zero.\n```\nbool isBoomerang(vector<vector<int>>& p) {\n return p[0][0] * (p[1][1] - p[2][1]) + p[1][0] * (p[2][1] - p[0][1]) + p[2][0] * (p[0][1] - p[1][1]) != 0;\n}\n```
71
2
[]
10