|
| 1 | +let eratosthenesSieve; |
| 2 | + |
| 3 | +/** |
| 4 | + * @param {number} n |
| 5 | + */ |
| 6 | +function initEratosthenesSieve(n) { |
| 7 | + eratosthenesSieve = Array(n + 1).fill(1); |
| 8 | + eratosthenesSieve[0] = 0; |
| 9 | + eratosthenesSieve[1] = 0; |
| 10 | + |
| 11 | + for (let i = 2; i <= n; i++) { |
| 12 | + if (eratosthenesSieve[i]) { |
| 13 | + for (let j = 2 * i; j <= n; j += i) { |
| 14 | + eratosthenesSieve[j] = 0; |
| 15 | + } |
| 16 | + } |
| 17 | + } |
| 18 | +} |
| 19 | +initEratosthenesSieve(100000); |
| 20 | + |
| 21 | +/** |
| 22 | + * @typedef {{ parent: number, children: number[], p0: number, p1: number, res }} TNode |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number} n |
| 27 | + * @param {number[][]} edges |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +var countPaths = function(n, edges) { |
| 31 | + /** @type {TNode[]} */ |
| 32 | + let nodes = [undefined]; |
| 33 | + |
| 34 | + for (let i = 1; i <= n; i++) nodes.push({ |
| 35 | + parent: 0, |
| 36 | + children: [], |
| 37 | + p0: 0, |
| 38 | + p1: 0, |
| 39 | + }); |
| 40 | + |
| 41 | + for (let [u,v] of edges) { |
| 42 | + nodes[u].children.push(v); |
| 43 | + nodes[v].children.push(u); |
| 44 | + } |
| 45 | + |
| 46 | + function buildRoot(x, parent) { |
| 47 | + const node = nodes[x]; |
| 48 | + node.parent = parent; |
| 49 | + |
| 50 | + for (let c of node.children) { |
| 51 | + if (c !== parent) buildRoot(c, x) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + buildRoot(1); |
| 56 | + let res = 0; |
| 57 | + |
| 58 | + function dp(x) { |
| 59 | + const isPrime = eratosthenesSieve[x]; |
| 60 | + const node = nodes[x]; |
| 61 | + let exc = 0; |
| 62 | + let cp0 = 0; |
| 63 | + let cp1 = 0; |
| 64 | + |
| 65 | + for (let c of node.children) { |
| 66 | + if (c !== node.parent) { |
| 67 | + dp(c); |
| 68 | + let nodeC = nodes[c]; |
| 69 | + cp0 += nodeC.p0; |
| 70 | + cp1 += nodeC.p1; |
| 71 | + |
| 72 | + if (isPrime) { |
| 73 | + exc += nodeC.p0 * (nodeC.p0 - 1) / 2 - nodeC.p0; |
| 74 | + } |
| 75 | + else { |
| 76 | + exc += nodeC.p0 * nodeC.p1; |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + if (isPrime) { |
| 82 | + node.p0 = 0; |
| 83 | + node.p1 = cp0 + 1; |
| 84 | + res += cp0 * (cp0 - 1) / 2 - exc; |
| 85 | + } |
| 86 | + else { |
| 87 | + node.p0 = cp0 + 1; |
| 88 | + node.p1 = cp1; |
| 89 | + res += (cp0 + 1) * cp1 - exc |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + dp(1); |
| 94 | + |
| 95 | + return res; |
| 96 | +}; |
| 97 | + |
0 commit comments