forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.kt
63 lines (52 loc) · 1.48 KB
/
1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
class DSU(val n: Int) {
val parent = IntArray(n + 1) {it}
val rank = IntArray(n + 1) {1}
var components = n
fun find(x: Int): Int {
if (parent[x] != x)
parent[x] = find(parent[x])
return parent[x]
}
fun union(x: Int, y: Int): Boolean {
val pX = find(x)
val pY = find(y)
if (pY == pX)
return false
if (rank[pX] > rank[pY]) {
rank[pX] += rank[pY]
parent[pY] = pX
} else {
rank[pY] += rank[pX]
parent[pX] = pY
}
components--
return true
}
fun connected() = components == 1
}
fun maxNumEdgesToRemove(n: Int, edges: Array<IntArray>): Int {
val a = DSU(n)
val b = DSU(n)
var edgeAdded = 0
for ((type, u, v) in edges) {
if (type == 3) {
if (a.union(u, v) or b.union(u, v))
edgeAdded++
}
}
for ((type, u, v) in edges) {
when (type) {
1 -> {
if (a.union(u, v))
edgeAdded++
}
2 -> {
if (b.union(u, v))
edgeAdded++
}
}
}
return if (a.connected() && b.connected()) edges.size - edgeAdded else -1
}
}