Skip to content

Commit 5dcbf9a

Browse files
authored
Create 3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js
1 parent 4955878 commit 5dcbf9a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* @param {number[][]} edges1
3+
* @param {number[][]} edges2
4+
* @param {number} k
5+
* @return {number[]}
6+
*/
7+
var maxTargetNodes = function (edges1, edges2, k) {
8+
const n = edges1.length + 1
9+
const m = edges2.length + 1
10+
11+
const adj1 = Array.from({ length: n }, () => [])
12+
const adj2 = Array.from({ length: m }, () => [])
13+
14+
for (const edge of edges1) {
15+
const [u, v] = edge
16+
adj1[u].push(v)
17+
adj1[v].push(u)
18+
}
19+
for (const edge of edges2) {
20+
const [u, v] = edge
21+
adj2[u].push(v)
22+
adj2[v].push(u)
23+
}
24+
25+
const good1 = new Array(n).fill(0)
26+
const good2 = new Array(m).fill(0)
27+
28+
for (let i = 0; i < n; i++) {
29+
dfs(i, -1, 0, i, k + 1, good1, adj1)
30+
}
31+
32+
for (let i = 0; i < m; i++) {
33+
dfs(i, -1, 0, i, k, good2, adj2)
34+
}
35+
36+
const mx = Math.max(...good2)
37+
38+
const res = new Array(n)
39+
for (let i = 0; i < n; i++) {
40+
res[i] = good1[i] + mx
41+
}
42+
return res
43+
}
44+
45+
function dfs(node, parent, distance, root, k, good, adj) {
46+
if (distance >= k) return
47+
good[root]++
48+
for (const neighbor of adj[node]) {
49+
if (neighbor !== parent) {
50+
dfs(neighbor, node, distance + 1, root, k, good, adj)
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)