Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1c809b7

Browse files
Create 3553-minimum-weighted-subgraph-with-the-required-paths-ii.js
1 parent 204e7fe commit 1c809b7

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* @param {number[][]} edges
3+
* @param {number[][]} queries
4+
* @return {number[]}
5+
*/
6+
var minimumWeight = function (edges, queries) {
7+
const n = edges.length + 1
8+
const adj = Array.from({ length: n }, () => [])
9+
for (const [u, v, w] of edges) {
10+
adj[u].push([v, w])
11+
adj[v].push([u, w])
12+
}
13+
14+
const parent = Array.from({ length: n }, (_, i) => i)
15+
const size = Array(n).fill(1)
16+
17+
function findSet(v) {
18+
while (parent[v] !== v) {
19+
v = parent[v]
20+
parent[v] = parent[parent[v]]
21+
}
22+
return v
23+
}
24+
25+
function unionSets(a, b) {
26+
a = findSet(a)
27+
b = findSet(b)
28+
if (size[a] < size[b]) {
29+
;[a, b] = [b, a]
30+
}
31+
parent[b] = a
32+
size[a] += size[b]
33+
return a
34+
}
35+
36+
const queriesByV = Array.from({ length: n }, () => [])
37+
for (let i = 0; i < queries.length; i++) {
38+
const [a, b, c] = queries[i]
39+
queriesByV[a].push([b, c, i])
40+
queriesByV[b].push([c, a, i])
41+
queriesByV[c].push([a, b, i])
42+
}
43+
44+
const visited = Array(n).fill(false)
45+
const ancestor = Array.from({ length: n }, (_, i) => i)
46+
const dist = Array(n).fill(0)
47+
const res = Array(queries.length).fill(0)
48+
49+
function dfs(v) {
50+
visited[v] = true
51+
52+
for (const [b, c, i] of queriesByV[v]) {
53+
res[i] += dist[v]
54+
if (visited[b]) {
55+
res[i] -= dist[ancestor[findSet(b)]]
56+
}
57+
if (visited[c]) {
58+
res[i] -= dist[ancestor[findSet(c)]]
59+
}
60+
}
61+
62+
for (const [u, w] of adj[v]) {
63+
if (visited[u]) {
64+
continue
65+
}
66+
67+
dist[u] = dist[v] + w
68+
dfs(u)
69+
ancestor[unionSets(v, u)] = v
70+
}
71+
}
72+
73+
dfs(0)
74+
return res
75+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /