Skip to content

Commit cce100b

Browse files
authored
Create 1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.kt
1 parent a923ce5 commit cce100b

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Solution {
2+
3+
class UnionFind(val n: Int) {
4+
val par = IntArray (n) { it }
5+
val rank = IntArray (n) { 1 }
6+
7+
fun find(x: Int): Int {
8+
if (par[x] != x)
9+
par[x] = find(par[x])
10+
return par[x]
11+
}
12+
13+
fun union(x: Int, y: Int): Boolean {
14+
val px = find(x)
15+
val py = find(y)
16+
if (px == py) return false
17+
if (rank[px] > rank[py]) {
18+
par[py] = px
19+
rank[px] += rank[py]
20+
} else {
21+
par[px] = py
22+
rank[py] += rank[px]
23+
}
24+
return true
25+
}
26+
}
27+
28+
fun findCriticalAndPseudoCriticalEdges(n: Int, _edges: Array<IntArray>): List<List<Int>> {
29+
val edges = _edges.mapIndexed { i, v ->
30+
intArrayOf(v[0], v[1], v[2], i)
31+
}.sortedWith(
32+
Comparator { a, b ->
33+
a[2] - b[2]
34+
}
35+
)
36+
37+
var mstWeight = 0
38+
val uf = UnionFind (n)
39+
for ((u, v, w, i) in edges) {
40+
if (uf.union(u, v)) mstWeight += w
41+
}
42+
43+
val crit = mutableListOf<Int>()
44+
val pseudo = mutableListOf<Int>()
45+
for ((u, v, w, i) in edges) {
46+
val uf2 = UnionFind (n)
47+
var mstWeightWithout = 0
48+
for ((u2, v2, w2, i2) in edges) {
49+
if (i != i2 && uf2.union(u2, v2)) mstWeightWithout += w2
50+
}
51+
if (uf2.rank.max()!! != n || mstWeightWithout > mstWeight) {
52+
crit.add(i)
53+
continue
54+
}
55+
56+
val uf3 = UnionFind (n)
57+
uf3.union(u, v)
58+
var mstWeightWith = w
59+
for ((u3, v3, w3, i3) in edges) {
60+
if (uf3.union(u3, v3)) mstWeightWith += w3
61+
}
62+
if (mstWeightWith == mstWeight) pseudo.add(i)
63+
}
64+
65+
return listOf(crit, pseudo)
66+
}
67+
}

0 commit comments

Comments
 (0)