Skip to content

Commit c39d3f2

Browse files
committed
1
1 parent 4f27387 commit c39d3f2

File tree

2 files changed

+112
-0
lines changed

2 files changed

+112
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package p28xx
2+
3+
import util.expect
4+
import java.util.*
5+
6+
fun main() {
7+
class Solution {
8+
fun maxKDivisibleComponents(n: Int, edges: Array<IntArray>, values: IntArray, k: Int): Int {
9+
class Group {
10+
var sum = 0L
11+
12+
var innerParent: Group? = null
13+
private set
14+
15+
var parent: Group
16+
set(value) {
17+
innerParent = value
18+
value.sum += sum
19+
}
20+
get() {
21+
return innerParent?.parent?.also {
22+
innerParent = it
23+
} ?: this
24+
}
25+
26+
fun join(target: Group) {
27+
val leftParent = parent
28+
val rightParent = target.parent
29+
30+
if (leftParent != rightParent) {
31+
leftParent.parent = rightParent
32+
}
33+
}
34+
}
35+
36+
val adjacent = Array(n) {
37+
hashSetOf<Int>()
38+
}
39+
40+
val degrees = IntArray(n)
41+
edges.forEach { (from, to) ->
42+
adjacent[from].add(to)
43+
adjacent[to].add(from)
44+
45+
degrees[from]++
46+
degrees[to]++
47+
}
48+
49+
val groups = arrayOfNulls<Group>(n)
50+
51+
val tasks = LinkedList<Int>()
52+
degrees.forEachIndexed { index, degree ->
53+
if (degree <= 1) {
54+
tasks += index
55+
}
56+
}
57+
58+
var result = 0
59+
while (tasks.isNotEmpty()) {
60+
val nodeIndex = tasks.poll()
61+
62+
if (groups[nodeIndex] != null) {
63+
continue
64+
}
65+
66+
val group = Group().also { it.sum = values[nodeIndex].toLong() }
67+
groups[nodeIndex] = group
68+
69+
adjacent[nodeIndex].forEach {
70+
groups[it]?.also {
71+
group.join(it)
72+
} ?: run {
73+
degrees[it]--
74+
if (degrees[it] <= 1) {
75+
tasks += it
76+
}
77+
}
78+
}
79+
80+
if (group.parent.sum % k == 0L) {
81+
result++
82+
}
83+
}
84+
85+
return result
86+
}
87+
}
88+
89+
expect {
90+
Solution().maxKDivisibleComponents(
91+
1, arrayOf(
92+
), intArrayOf(0), 1
93+
)
94+
}
95+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package p35xx
2+
3+
import util.expect
4+
5+
fun main() {
6+
class Solution {
7+
fun minOperations(nums: IntArray, k: Int): Int {
8+
return nums.sum() % k
9+
}
10+
}
11+
12+
expect {
13+
Solution().minOperations(
14+
intArrayOf(), 2
15+
)
16+
}
17+
}

0 commit comments

Comments
 (0)