Skip to content

Commit cc1ba7f

Browse files
authored
Create 1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.js
1 parent e3bcd24 commit cc1ba7f

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} n
3+
* @param {number[][]} edges
4+
* @return {number}
5+
*/
6+
const maxNumEdgesToRemove = function (n, edges) {
7+
edges.sort((a, b) => b[0] - a[0])
8+
let edgesAdded = 0
9+
const bob = new UnionFind(n)
10+
const alice = new UnionFind(n)
11+
for (let edge of edges) {
12+
let type = edge[0],
13+
one = edge[1],
14+
two = edge[2]
15+
switch (type) {
16+
case 3:
17+
edgesAdded += bob.unite(one, two) | alice.unite(one, two)
18+
break
19+
case 2:
20+
edgesAdded += bob.unite(one, two)
21+
break
22+
case 1:
23+
edgesAdded += alice.unite(one, two)
24+
break
25+
}
26+
}
27+
return bob.united() && alice.united() ? edges.length - edgesAdded : -1
28+
}
29+
class UnionFind {
30+
constructor(n) {
31+
this.component = []
32+
this.distinctComponents = n
33+
for (let i = 0; i <= n; i++) this.component.push(i)
34+
}
35+
unite(a, b) {
36+
const ar = this.find(a)
37+
if (ar !== this.find(b)) {
38+
this.component[ar] = b
39+
this.distinctComponents--
40+
return true
41+
}
42+
return false
43+
}
44+
find(a) {
45+
if (this.component[a] != a) {
46+
this.component[a] = this.find(this.component[a])
47+
}
48+
return this.component[a]
49+
}
50+
united() {
51+
return this.distinctComponents === 1
52+
}
53+
}

0 commit comments

Comments
 (0)