Skip to content

Commit f18d8b9

Browse files
authored
Create 3108-minimum-cost-walk-in-weighted-graph.js
1 parent e6e824b commit f18d8b9

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @param {number[][]} query
5+
* @return {number[]}
6+
*/
7+
var minimumCost = function (n, edges, query) {
8+
const map = new Map()
9+
const ufs = new UFS(n)
10+
11+
for (let i = 0; i < edges.length; i++) {
12+
const [a, b, e] = edges[i]
13+
ufs.union(a, b)
14+
}
15+
16+
for (let i = 0; i < edges.length; i++) {
17+
const [a, b, e] = edges[i]
18+
const rootA = ufs.find(a)
19+
const rootB = ufs.find(b)
20+
21+
const root = ufs.find(a)
22+
let tmp = e
23+
if (map.has(rootA)) {
24+
tmp = e & map.get(rootA)
25+
}
26+
if (map.has(rootB)) {
27+
tmp = e & map.get(rootB)
28+
}
29+
map.set(root, tmp)
30+
}
31+
32+
const ans = []
33+
for (let i = 0; i < query.length; i++) {
34+
const [s, t] = query[i]
35+
const rootA = ufs.find(s)
36+
const rootB = ufs.find(t)
37+
38+
if (rootA !== rootB) {
39+
ans.push(-1)
40+
} else if (s === t) {
41+
ans.push(0)
42+
} else {
43+
ans.push(map.get(rootA))
44+
}
45+
}
46+
47+
return ans
48+
}
49+
50+
class UFS {
51+
constructor(n) {
52+
this.parent = new Array(n).fill(0).map((_, i) => i)
53+
this.rank = new Array(n).fill(0)
54+
this.size = n
55+
this.sz = new Array(n).fill(1)
56+
}
57+
58+
find(x) {
59+
if (x !== this.parent[x]) {
60+
this.parent[x] = this.find(this.parent[x])
61+
}
62+
return this.parent[x]
63+
}
64+
65+
union(x, y) {
66+
const px = this.find(x)
67+
const py = this.find(y)
68+
69+
if (px === py) {
70+
return false
71+
}
72+
73+
if (this.rank[px] > this.rank[py]) {
74+
this.parent[py] = px
75+
this.sz[px] += this.sz[py]
76+
} else if (this.rank[px] < this.rank[py]) {
77+
this.parent[px] = py
78+
this.sz[py] += this.sz[px]
79+
} else {
80+
this.parent[px] = py
81+
this.sz[py] += this.sz[px]
82+
this.rank[px]++
83+
}
84+
85+
this.size--
86+
return true
87+
}
88+
89+
reset() {
90+
this.parent = new Array(n).fill(0).map((_, i) => i)
91+
this.rank = new Array(n).fill(0)
92+
this.size = n
93+
}
94+
}

0 commit comments

Comments
 (0)