Skip to content

Commit 3212f86

Browse files
authored
Create 3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js
1 parent 5dcbf9a commit 3212f86

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
class Graph {
2+
constructor(n) {
3+
this.n = n
4+
this.adj = Array.from({ length: n }, () => [])
5+
this.weight = new Map()
6+
for (let i = 0; i < n; i++) {
7+
this.weight.set(i, new Map())
8+
}
9+
}
10+
11+
addEdgeOri(i, j, w = 0) {
12+
this.adj[i].push(j)
13+
this.weight.get(i).set(j, w)
14+
}
15+
16+
addEdge(i, j, w = 0) {
17+
// Add w to v's list.
18+
this.adj[i].push(j)
19+
// Add v to w's list
20+
this.adj[j].push(i)
21+
this.weight.get(i).set(j, w)
22+
this.weight.get(j).set(i, w)
23+
}
24+
}
25+
26+
function dijkstra(graph, source) {
27+
const ans = new Array(graph.n).fill(Number.MAX_SAFE_INTEGER / 2)
28+
const pq = new MinPriorityQueue({ priority: (item) => item[1] })
29+
pq.enqueue([source, 0])
30+
31+
while (pq.size() > 0) {
32+
const [item, dis] = pq.dequeue().element
33+
if (ans[item] <= dis) continue
34+
ans[item] = dis
35+
36+
graph.adj[item].forEach((neighbor) => {
37+
if (ans[neighbor] >= Number.MAX_SAFE_INTEGER / 2) {
38+
pq.enqueue([neighbor, dis + graph.weight.get(item).get(neighbor)])
39+
}
40+
})
41+
}
42+
return ans
43+
}
44+
45+
function maxTargetNodes(edges1, edges2) {
46+
const n = edges1.length + 1
47+
const m = edges2.length + 1
48+
const g1 = new Graph(n)
49+
const g2 = new Graph(m)
50+
51+
edges1.forEach(([a, b]) => g1.addEdge(a, b, 1))
52+
edges2.forEach(([a, b]) => g2.addEdge(a, b, 1))
53+
54+
const dis1 = dijkstra(g1, 0)
55+
const dis2 = dijkstra(g2, 0)
56+
57+
const a0 = new Set()
58+
const a1 = new Set()
59+
const b0 = new Set()
60+
const b1 = new Set()
61+
62+
for (let i = 0; i < dis1.length; i++) {
63+
if (dis1[i] % 2 === 0) {
64+
a0.add(i)
65+
} else {
66+
a1.add(i)
67+
}
68+
}
69+
70+
for (let i = 0; i < dis2.length; i++) {
71+
if (dis2[i] % 2 === 0) {
72+
b0.add(i)
73+
} else {
74+
b1.add(i)
75+
}
76+
}
77+
78+
const b = Math.max(b0.size, b1.size)
79+
const ans = []
80+
81+
for (let i = 0; i < n; i++) {
82+
if (a0.has(i)) {
83+
ans.push(a0.size + b)
84+
} else {
85+
ans.push(a1.size + b)
86+
}
87+
}
88+
89+
return ans
90+
}

0 commit comments

Comments
 (0)